elliot
elliot

Reputation: 1944

Drop list columns from dataframe using dplyr and select_if

Is it possible to drop all list columns from a dataframe using dpyr select similar to dropping a single column?

df <- tibble(
  a = LETTERS[1:5],
  b = 1:5,
  c = list('bob', 'cratchit', 'rules!','and', 'tiny tim too"')
)


df %>% 
  select_if(-is.list)

Error in -is.list : invalid argument to unary operator

This seems to be a doable work around, but was wanting to know if it can be done with select_if.

df %>%
  select(-which(map(df,class) == 'list'))

Upvotes: 5

Views: 485

Answers (2)

akrun
akrun

Reputation: 886998

We can use Filter from base R

Filter(Negate(is.list), df)
# A tibble: 5 x 2
#  a         b
#  <chr> <int>
#1 A         1
#2 B         2
#3 C         3
#4 D         4
#5 E         5

Upvotes: 3

markus
markus

Reputation: 26343

Use Negate

df %>% 
  select_if(Negate(is.list))
# A tibble: 5 x 2
  a         b
  <chr> <int>
1 A         1
2 B         2
3 C         3
4 D         4
5 E         5

There is also purrr::negate that would give the same result.

Upvotes: 3

Related Questions