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

How to convert a list of tables into one big table in R

使用 R ...我有一个 table 的列表。

# 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

我想 "collapse"(不确定这是不是正确的词)这个列表到一个超级 table,因为列变量对于每个 table 都是相同的名单。我希望输出看起来像我在下面写的那样......有什么办法吗?我尝试使用 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

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

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
...