5

我有以下数据框:

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和与该组合相关x2freqfrom 数据框 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

关于如何解决这个问题的任何想法?

4

2 回答 2

6

不要使x1x2因素。只需使用向量。用于%in%逻辑测试。

sp <- combn(c("sp1","sp2","sp3","sp4"),2)
d <- data.frame(t(sp),"freq"=sample(0:100,6))
x1 <- c("sp1","sp2")
x2 <- c("sp3","sp4")
sub <- d[d$X1 %in% x1 & d$X2 %in% x2,]
于 2012-06-19T10:56:51.133 回答
5

你快到了:

d[d$X1 %in% x1 & d$X2 %in% x2,]
于 2012-06-19T10:56:03.643 回答