Remove a dataframe from a list of dataframes conditionally

Viewed 264

I have a list of dataframes from which I would like to remove the dataframes that have a particular value in a specific column.

Code

library(tidyverse)

combi <- function(a=c(1,2,3), b=c(2,3,4,5)){
  return(expand.grid(a,b))
}

df <- pmap(list(a=c(1,2,3)), combi)

Output

df
[[1]]
 Var1 Var2
1    1    2
2    1    3
3    1    4
4    1    5

[[2]]
  Var1 Var2
1    2    2
2    2    3
3    2    4
4    2    5

[[3]]
  Var1 Var2
1    3    2
2    3    3
3    3    4
4    3    5

Let's say I would like to remove a dataframe, if Var1==2.

How do you tackle this problem in the Tidyverse?

1 Answers

You can use discard in purrr

purrr::discard(df, ~any(.x$Var1 == 2))
#Or using keep
#purrr::keep(df, ~any(.x$Var1 != 2))

#[[1]]
#  Var1 Var2
#1    1    2
#2    1    3
#3    1    4
#4    1    5

#[[2]]
#  Var1 Var2
#1    3    2
#2    3    3
#3    3    4
#4    3    5

Or Filter in base R :

Filter(function(x) any(x$Var1 != 2), df)

Some variations :

df[sapply(df, function(x) any(x$Var1 != 2))]
df[purrr::map_lgl(df, ~any(.x$Var1 != 2))]
Related