过去我问了一个关于如何create cross tables from a list view的问题。我被建议使用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
...
任何人都能指出我将有助于实现这一目标的功能吗?
答案 0 :(得分: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
答案 1 :(得分: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
# ...