R语言 如何获取满足列范围条件的行?

lsmepo6l  于 2023-01-28  发布在  其他
关注(0)|答案(2)|浏览(546)

我希望我的问题格式正确,因此请遵循下一个示例
假设我有一个如下所示的 Dataframe :

df <- data.frame <- name = c('sai','ram','deepika','sahithi','kumar','scott','Don','Lin'),
  number = c(0,1,2,3,1,0,2,1),
  number2different c(0,1,1,1,2,1,1,0),
  number3differentname = c(0,1,0,1,2,0,1,2)

如果想要选择或创建一个子集,其中只有名为name的列中的行显示所有其他列的值为0,例如Sai,它只有旁边的值等于0,哪个命令最有效?我试着搜索基于列选择行,但是条件总是针对单个列,有一种方法可以基于一系列列的条件选择行见面?非常感谢你的帮助,我真的很感激。

neskvpey

neskvpey1#

您可以使用tidyverse“filter”,并使用“&"表示多个条件:

df %>% filter(number == 0 & number2different == 0 & number3different == 0)
bnlyeluc

bnlyeluc2#

# Sample Data
df <- data.frame(name = c('sai','ram','deepika','sahithi','kumar','scott','Don','Lin'),
  number = c(0,1,2,3,1,0,2,1),
  number2different = c(0,1,1,1,2,1,1,0),
  number3differentname = c(0,1,0,1,2,0,1,2))

# Subsetting by the 'name' column those rows where all other columns equal zero
df$name[rowSums(df[names(df) != "name"]) == 0]

# Subsetting by row where the specified columns sum to zero
df[rowSums(df[names(df) != "name"]) == 0,]

# Subsetting by row where the specified columns fall within the range (1:2)
df[rowSums(sapply(df[names(df) != "name"], function(x) x >= 1 & x <= 2)) == ncol(df[names(df) != "name"]),]

相关问题