问题
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