[英]Filtering a data frame by factors in R
我有以下數據框:
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
所有可能組合以及與該組合相關聯的數據框d
中的freq
。
返回的數據幀如下所示:
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
關於如何解決此問題的任何想法?
您幾乎在那里:
d[d$X1 %in% x1 & d$X2 %in% x2,]
不要使x1
和x2
因子。 只需使用向量。 使用%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,]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.