rename_with doesn't work in purrr::map2 – Error "! the … list contains fewer than 2 elements"

Advertisements

Another seemingly easy task where purrr::map2 is giving me a hard time.

I have a list of data frames and I have a vector of column names. I now want to rename a certain column in each of the data frames with the respective new column name. So I wanted to simply loop through it with map2, but am getting an error. What am I doing wrong?

new_names <- c("test1", "test2")

df_list <- list(data.frame(mtcars[, 1]),
                data.frame(mtcars[, 2]))

map2(.x = df_list,
     .y = new_names,
     .f = ~.x |> 
       rename_with(.cols = everything(),
                   .fn   = ~.y))

# Error in `map2()`:
# ℹ In index: 1.
# Caused by error in `.fn()`:
# ! the ... list contains fewer than 2 elements
# Run `rlang::last_error()` to see where the error occurred.

I also tried different variants of ".y", e.g. !!.y, paste0(sym(.y)) etc. in all possible combinations – no success.

Expected output would be the same list as the input, just that the first data frame has now a column "test1" and the second data frame a column "test2".

>Solution :

The problem results from the conflict between .f from map2 and .fn from rename_with. You need to explicitly specify an argument name, i.e. change .fn = ~ .y to .fn = \(nms) .y.

map2(.x = df_list,
     .y = new_names,
     .f = ~ .x |> 
       rename_with(.cols = everything(),
                   .fn   = \(nms) .y))

Leave a Reply Cancel reply