如何在R中组合不同列数的表?

问题描述 投票:0回答:2

我知道这一定是一个简单的修复,但我已经坚持这个问题很多年了。我有三张表,两张有三列,一张有两列。我想将它们结合起来,以显示对于每个统计测试,特定模型有多少次是最好的。下面是我目前拥有的表格。组合它们的最佳方法是什么,以便我将 R_Squared、AIC 和 BIC 作为列标题,并将 Quadratic、Polynomial 和 Linear 作为带有结果的行名称(R Squared 列下的 Linear 为零)?非常感谢你的帮助!

r model data-manipulation data-management
2个回答
1
投票

不是最优雅的解决方案,但确实创建了所需的表格。

library(dplyr)

# Data
R_Squared <- data.frame(Polynomial = c(283), Quadratic = c(2))
AIC <- data.frame(Polynomial = c(201), Quadratic = c(60), Linear = c(24))
BIC <- data.frame(Polynomial = c(196), Quadratic = c(62), Linear = c(27))

df <- bind_rows(AIC, BIC, R_Squared)
# add row names
row.names(df) <- c('AIC','BIK','R_Squared')
# returns the transpose of df
df <- t(df)

输出:

           AIC BIK R_Squared
Polynomial 201 196       283
Quadratic   60  62         2
Linear      24  27        NA

0
投票

这是使用

table
对象执行此操作的另一种方法:

# Data 
R_Squared <- structure(
  data.frame(matrix(c(283,2), ncol = 2)),
  class = "table",
  dim = c(2),
  dimnames = list(
    c("Polynomial", "Quadratic")
  )
)
AIC <- structure(
  data.frame(matrix(c(201,60,24), ncol = 3)),
  class = "table",
  dim = c(3),
  dimnames = list(
    c("Polynomial", "Quadratic","Linear")
  )
)
BIC <- structure(
  data.frame(matrix(c(196,62,27), ncol = 3)),
  class = "table",
  dim = c(3),
  dimnames = list(
    c("Polynomial", "Quadratic","Linear")
  )
)

这些是输出

table()
后的虚拟对象。现在我们用
list
制作这些表的
mget
并识别唯一的列。

## combine 
mylist <- mget(c("R_Squared", "AIC", "BIC"))
cols <- unique(unlist(sapply(mylist, names)))

之后,考虑到同名的差异,我们将所有内容与

setdiff()
结合起来:

do.call(rbind, lapply(mylist, function(x) {
  x[setdiff(cols, names(x))] <- NA
  x
}))

#          Polynomial Quadratic Linear
#R_Squared 283        2         NA    
#AIC       201        60        24    
#BIC       196        62        27 

希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.