Home > other >  How to get rows where a condition in range of columns is meet?
How to get rows where a condition in range of columns is meet?

Time:01-24

I hope I am formatting my question right so following the next example

Lets say I have a dataframe that looks like this:

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)

And if wanted to select or create a subset where only the rows from the column called name showed where all the other columns had a value of 0 for example Sai which only has values next to it that equal 0 which command would work the best? I tried searching about selecting row based on columns but the conditions are always for a single column its there a way to select rows based on conditions for a range of columns to be meet? Thanks a lot for your help i really appreciate it.

CodePudding user response:

You could use tidyverse "filter" with multiple conditions using "&":

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

CodePudding user response:

# 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]
  •  Tags:  
  • r
  • Related