I have the following dataframe:
sp <- combn(c("sp1","sp2","sp3","sp4"),2)
d <- data.frame(t(sp),"freq"=sample(0:100,6))
and two factors
x1 <- as.factor(c("sp1","sp2"))
x2 <- as.factor(c("sp3","sp4"))
I need a dataframe returned containing all possible combinations of x1 and x2 and the freq from dataframe d associated with this combination.
The returned dataframe would look like this:
data.frame("X1" = c("sp1","sp1","sp2","sp2"),
"X2" = c("sp3","sp4","sp3","sp4"),
"freq" = c(4,94,46,74))
I have tried:
sub <- d[d$X1 == x1 & d$X2 == x2,]
but get the error
Error in Ops.factor(d$X1, x1) : level sets of factors are different
Any ideas on how to solve this problem?
Do not make
x1andx2factors. Just use vectors. Use%in%for the logical test.