1

使用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
4

1 回答 1

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
...
于 2015-03-13T19:07:31.753 回答