2

过去我问过一个关于如何从列表视图创建交叉表的问题。我被推荐xtabs用于这个,效果很好。今天,我一直在寻找相反的方法并从交叉表创建列表视图表。我希望找到一个反向公式,但没有成功。我相信有一个预定义的功能,但无法找到它。

我有下表:

# load table     
crosstable <- structure(list(col1 = c(0, 0, 1, 0, 0, 0, 0, 0, 0), col2 = c(0, 1, 0, 0, 0, 0, 0, 0, 0), col3 = c(0, 0, 0, 0, 0, 0, 0, 0, 1), col4 = c(1, 0, 0, 0, 0, 0, 0, 0, 0), col5 = c(0, 0, 0, 0, 0, 0, 0, 1, 0), col6 = c(0, 0, 0, 0, 0, 1, 0, 0, 0), col7 = c(0, 0, 0, 0, 1, 0, 0, 0, 0), col8 = c(0, 0, 0, 0, 0, 0, 1, 0, 0)), .Names = c("col1", "col2", "col3", "col4", "col5", "col6", "col7", "col8"), row.names = c("row1", "row2", "row3", "row4", "row5", "row6", "row7", "row8", "row9"), class = "data.frame")

#display table
crosstable

     col1 col2 col3 col4 col5 col6 col7 col8
row1    0    0    0    1    0    0    0    0
row2    0    1    0    0    0    0    0    0
row3    1    0    0    0    0    0    0    0
row4    0    0    0    0    0    0    0    0
row5    0    0    0    0    0    0    1    0
row6    0    0    0    0    0    1    0    0
row7    0    0    0    0    0    0    0    1
row8    0    0    0    0    1    0    0    0
row9    0    0    1    0    0    0    0    0

我想将其转换为显示如下内容的表格:

row1 col1 0
row1 col2 0
row1 col3 0
row1 col4 1
row1 col5 0
...

任何人都可以为我指明有助于实现这一目标的功能方向吗?

4

2 回答 2

4

坚持使用基础 R,您可以使用stack

CTLong <- data.frame(rows = rownames(crosstable), stack(crosstable))
CTLong <- CTLong[order(CTLong$rows), ]
head(CTLong)
   rows values  ind
1  row1      0 col1
10 row1      0 col2
19 row1      0 col3
28 row1      1 col4
37 row1      0 col5
46 row1      0 col6
于 2013-02-20T07:30:22.463 回答
2

你可以reshape2::melt用来获得:

library(reshape2)
melt(cbind(rownames(crosstable),crosstable))
# Using rownames(crosstable) as id variables
#    rownames(crosstable) variable value
# 1                  row1     col1     0
# 2                  row2     col1     0
# 3                  row3     col1     1
# 4                  row4     col1     0
# 5                  row5     col1     0
# 6                  row6     col1     0
# 7                  row7     col1     0
# ...
于 2013-02-20T07:29:05.217 回答