How to use select within map for a list of dataframes

Viewed 919

I have a list of dataframes each with the same columns. I want to drop some columns by index. How do I use a select command within a map function?

Here is my attempt:

data <- data %>% map(~ select(-c(7, 11, 13, 14))) 

Any ideas on how I need to change this code?

Many thanks

2 Answers

You can try :

data <- purrr::map(data, ~ . %>% dplyr::select(-c(7, 11, 13, 14))) 

Or in base R :

data <- lapply(data, function(x) x[,-c(7, 11, 13, 14)])

Update

This worked for me with dplyr > 0.8

data <- map(data, .f = list(. %>% dplyr::select(-grp)))

We can do this without anonymous function

data <- lapply(data, `[`, -c(7, 11, 13, 14))
Related