Finding the original vectors from an interaction table

萝らか妹 提交于 2019-12-10 19:52:26

问题


A = c(1,2,3,2,1,2,2,2,1,2,3,2,1)
B = c(2,3,2,3,2,2,1,1,2,1,2,2,3)
mytable = table(A,B)

What is the best solution to find back the two vectors from mytable? Of course, it will not be the exact same vectors but the order of A compared to B has to be respected. Does it make sense?


回答1:


You can use data.frame and rep:

X <- as.data.frame(mytable)
X[] <- lapply(X, function(z) type.convert(as.character(z)))
Y <- X[rep(rownames(X), X$Freq), 1:2]
Y
#     A B
# 2   2 1
# 2.1 2 1
# 2.2 2 1
# 4   1 2
# 4.1 1 2
# 4.2 1 2
# 5   2 2
# 5.1 2 2
# 6   3 2
# 6.1 3 2
# 7   1 3
# 8   2 3
# 8.1 2 3

Y$A contains the same values as A, and Y$B contains the same values as B.

all.equal(sort(Y$A), sort(A))
# [1] TRUE
all.equal(sort(Y$B), sort(B))
# [1] TRUE

Alternatively, with @Matthew's comments:

X <- data.matrix(data.frame(mytable))
X[rep(sequence(nrow(X)), X[, "Freq"]), 1:2]

The result in this case is a two-column matrix.


Update (more than a year later)

You can also use expandRows from my "splitstackshape" package after converting the table to a data.table. Notice that it also gives you a message about what combinations had zero values, and were thus dropped when expanding to a long form.

library(splitstackshape)
expandRows(as.data.table(mytable), "N")
# The following rows have been dropped from the input: 
# 
# 1, 3, 9
# 
#     A B
#  1: 2 1
#  2: 2 1
#  3: 2 1
#  4: 1 2
#  5: 1 2
#  6: 1 2
#  7: 2 2
#  8: 2 2
#  9: 3 2
# 10: 3 2
# 11: 1 3
# 12: 2 3
# 13: 2 3


来源:https://stackoverflow.com/questions/19841768/finding-the-original-vectors-from-an-interaction-table

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!