Subset data based on same condition across multiple columns

Viewed 32

I'm stuck trying to make a subsetting code. I want to subset/select rows of data based on the same condition across a large number of columns. So in the below example I want to select rows where any of the 'year' columns that has values greater than 1.

Data have:

ID 1970 1971 1972....2020
599  0    0   0       1
628  3    1   0       0
788  1    0   0       1
111  0    0   1       0   
222  0    2   1       1

Data want:

628  3    1   0       0
222  0    2   1       1

I tried this dpylr code without success.

select <- df %>% 
  filter(vars(starts_with(c("1","2")), any_vars(. > 1))
2 Answers

You could use if_any():

library(dplyr)

df %>%
  filter(if_any(-ID, ~ .x > 1))

or the superseded filter_at():

df %>% 
  filter_at(vars(-ID), any_vars(. > 1))

Try this:

inds <- {DF[, -1] > 1} |> rowSums() |> as.logical()
DF[inds, ]
#>    id y1970 y1971 y1972 y2020
#> 2 628     3     1     0     0
#> 5 222     0     2     1     1

Reprex:

DF <- data.frame(
  id = c(599, 628, 788, 111, 222), 
  y1970 = c(0, 3, 1, 0, 0), 
  y1971 = c(0, 1, 0, 0, 2), 
  y1972 = c(0, 0, 0, 1, 1), 
  y2020 = c(1, 0, 1, 0, 1)
)
DF
#>    id y1970 y1971 y1972 y2020
#> 1 599     0     0     0     1
#> 2 628     3     1     0     0
#> 3 788     1     0     0     1
#> 4 111     0     0     1     0
#> 5 222     0     2     1     1

Created on 2022-08-18 by the reprex package (v2.0.1)

Related