在 R 中使用 OR 而不是 AND 根据多个条件选择行
Selecting rows based on multiple conditions using OR instead of AND in R
我有一个大型数据集,我正尝试根据 2 个单独列的值对其进行过滤。对于每一行,我都有一列显示它们的总计数 (tot) 和一列显示看到该类型样本的总次数 (tot.type)。
我想根据 (tot) 和 (tot.type) 过滤我的数据,例如,其中 (tot) 或 (tot.type) 必须大于或等于 2。
我找到的所有基于多个值进行过滤的示例都使用 "AND",但在您使用 "OR" 的地方没有...
Example data:
name = c("A","B","C","D","E")
rx = c(1,0,2,1,1)
ry = c(0,1,1,0,0)
rz = c(0,0,2,2,3)
type = c("p","q","r","p","r")
tot = c(1,1,5,3,4)
tot.type = c(2,1,2,2,2)
test = data.frame(name,rx,ry,rz,tot,tot.type)
在此示例中,我将丢弃 B 行,并保留其余部分。
我已经根据一列或另一列将数据过滤成 2 个单独的数据集,然后合并它们,但这是否可以在生成一个数据集的一行中完成,而不是做两个单独的数据集并合并他们以后呢?
尝试
test[test$tot>=2 | test$tot.type>=2,]
(p.s。我认为你的例子有错误,你想要
test = data.frame(name,rx,ry,rz,type,tot,tot.type)
而不是
test = data.frame(name,rx,ry,rz,tax,tot,N.tax)
?
您可以使用 rowSums
。 ("test" 根据@CactusWoman 的数据)
test[!!rowSums(test[c('tot', 'tot.type')]>=2),])
或其他选择
test[unique(which(test[c("tot","tot.type")] >= 2,
arr.ind = TRUE)[, 1]), ]
subset
正是为此设计的:
subset(test, tot.type >= 2 | tot >= 2)
我有一个大型数据集,我正尝试根据 2 个单独列的值对其进行过滤。对于每一行,我都有一列显示它们的总计数 (tot) 和一列显示看到该类型样本的总次数 (tot.type)。
我想根据 (tot) 和 (tot.type) 过滤我的数据,例如,其中 (tot) 或 (tot.type) 必须大于或等于 2。
我找到的所有基于多个值进行过滤的示例都使用 "AND",但在您使用 "OR" 的地方没有...
Example data:
name = c("A","B","C","D","E")
rx = c(1,0,2,1,1)
ry = c(0,1,1,0,0)
rz = c(0,0,2,2,3)
type = c("p","q","r","p","r")
tot = c(1,1,5,3,4)
tot.type = c(2,1,2,2,2)
test = data.frame(name,rx,ry,rz,tot,tot.type)
在此示例中,我将丢弃 B 行,并保留其余部分。
我已经根据一列或另一列将数据过滤成 2 个单独的数据集,然后合并它们,但这是否可以在生成一个数据集的一行中完成,而不是做两个单独的数据集并合并他们以后呢?
尝试
test[test$tot>=2 | test$tot.type>=2,]
(p.s。我认为你的例子有错误,你想要
test = data.frame(name,rx,ry,rz,type,tot,tot.type)
而不是
test = data.frame(name,rx,ry,rz,tax,tot,N.tax)
?
您可以使用 rowSums
。 ("test" 根据@CactusWoman 的数据)
test[!!rowSums(test[c('tot', 'tot.type')]>=2),])
或其他选择
test[unique(which(test[c("tot","tot.type")] >= 2,
arr.ind = TRUE)[, 1]), ]
subset
正是为此设计的:
subset(test, tot.type >= 2 | tot >= 2)