我有以下数据框:
sp <- combn(c("sp1","sp2","sp3","sp4"),2)
d <- data.frame(t(sp),"freq"=sample(0:100,6))
和两个因素
x1 <- as.factor(c("sp1","sp2"))
x2 <- as.factor(c("sp3","sp4"))
我需要一个返回的数据框,其中包含所有可能的组合x1
和与该组合相关x2
的freq
from 数据框 d
。
返回的数据框如下所示:
data.frame("X1" = c("sp1","sp1","sp2","sp2"),
"X2" = c("sp3","sp4","sp3","sp4"),
"freq" = c(4,94,46,74))
我努力了:
sub <- d[d$X1 == x1 & d$X2 == x2,]
但得到错误
Error in Ops.factor(d$X1, x1) : level sets of factors are different
关于如何解决这个问题的任何想法?