Apply function to each element of a list in R using purrr:map

I have been struggling into applying a custom function using dplyr to a list of tibbles. The following snippet works fine using a for loop:

df <- list(as_tibble(head(mtcars[, 1:2])), as_tibble(tail(mtcars[, 1:2])), as_tibble(mtcars[13:18, 1:2]))

for (d in seq_along(df)) { 
  df[[d]] <- df[[d]] %>% rename_all(toupper) 
}

According to purrr documentation, map: "(…) apply a function iteratively to each element of a list or vector", but throws an error:

map(df, rename_all(toupper))
Error in UseMethod("tbl_vars") : 
  no applicable method for 'tbl_vars' applied to an object of class "function"

I imagine it should be possible using map, but clearly I'm missing something :/

Note: this is close to Rename Columns of Data.frame in list, but I was asking in how to do it using the packages from tidyverse (purrr specifically) and not base R.

Upvotes: 2

Views: 2755

Answers (1)

markus
markus

Reputation: 26343

Because OP asked for a solution using purrr functions we can do

library(purrr); library(dplyr)
map(df, .f = ~ rename_all(.x, toupper))
# or map(df, .f = ~ set_names(.x, toupper(names(.x))))

#[[1]]
# A tibble: 6 x 2
#    MPG   CYL
#* <dbl> <dbl>
#1  21       6
#2  21       6
#3  22.8     4
#4  21.4     6
#5  18.7     8
#6  18.1     6

#[[2]]
# ...

The reason why OP's solution did not work is that rename_all expects a data.frame / tibble as first argument.

Upvotes: 4

Related Questions