Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading