如何将表列表转换为R中的一个大表

时间:2015-03-13 18:36:29

标签: r list statistics do.call

使用 R ...我有一个表格列表。

# Example data
z <- list(cbind(c(1,2), c(3,4)), cbind(c(1,2), c(3,4,5,6)), cbind(c(1,2), c(1,2,3,4,5,6)), cbind(c(1,2), c(3,4)), cbind(c(1,2), c(3,4,5,6,9,4,5,6)))
z <- setNames(z, c("Ethnicity", "Country", "Age Band", "Marital Status", "Hair Color"))

z

$Ethnicity
     [,1] [,2]
[1,]    1    3
[2,]    2    4

$Country
     [,1] [,2]
[1,]    1    3
[2,]    2    4
[3,]    1    5
[4,]    2    6

$`Age Band`
     [,1] [,2]
[1,]    1    1
[2,]    2    2
[3,]    1    3
[4,]    2    4
[5,]    1    5
[6,]    2    6

$`Marital Status`
     [,1] [,2]
[1,]    1    3
[2,]    2    4

$`Hair Color`
     [,1] [,2]
[1,]    1    3
[2,]    2    4
[3,]    1    5
[4,]    2    6
[5,]    1    9
[6,]    2    4
[7,]    1    5
[8,]    2    6

我想将这个列表“折叠”(不确定这是否是正确的词)到一个超级表中,因为列变量对于列表中的每个表都是相同的。我希望输出看起来像我在下面写的那样......有没有办法做到这一点?我尝试使用do.call(rbind, z),但这并没有给我正确的输出。

Ethnicity
[1,]    1    3
[2,]    2    4
Country
[1,]    1    3
[2,]    2    4
[3,]    1    5
[4,]    2    6
`Age Band`
[1,]    1    1
[2,]    2    2
[3,]    1    3
[4,]    2    4
[5,]    1    5
[6,]    2    6
`Marital Status`
[1,]    1    3
[2,]    2    4
`Hair Color`
[1,]    1    3
[2,]    2    4
[3,]    1    5
[4,]    2    6
[5,]    1    9
[6,]    2    4
[7,]    1    5
[8,]    2    6

1 个答案:

答案 0 :(得分:2)

如果我理解正确的话,这会产生你想要的输出:

sink("output.txt")
for (i in seq_along(z)) {
  cat(names(z)[i], '\n') # print out the header
  write.table(z[[i]], row.names = FALSE, col.names = FALSE)
}
sink()

我打开与sink的文本文件的连接,然后遍历您的表格列表并使用write.table打印出每个表格。

它产生以下输出:

Ethnicity 
1 3
2 4
Country 
1 3
2 4
1 5
2 6
Age Band 
1 1
2 2
1 3
2 4
1 5
2 6
...