Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop list columns from dataframe using dplyr and select_if

Tags:

list

r

dplyr

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'))
like image 300
elliot Avatar asked Dec 18 '18 12:12

elliot


2 Answers

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.

like image 174
markus Avatar answered Oct 21 '22 16:10

markus


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
like image 3
akrun Avatar answered Oct 21 '22 18:10

akrun