I have a named list and within that list I want to rename their columns based on the names the list comes from.
The probelm with my approach seems to be the .x placeholder, which I thought would be my unique list names. But within the rename_with function, it seems the .x is evaluated within each list data frame and not from the original .x. Is there any way I can carry forward the original .x (or list names) for renaming?
my_list <- list(L1 = data.frame(x=1:3),
L1 = data.frame(x=1:3),
L2 = data.frame(x=1:3),
L2 = data.frame(x=1:3))
my_list |>
purrr::map(.x = unique(names(my_list)),
.f = ~my_list[names(my_list) == .x] |>
dplyr::bind_rows() |>
dplyr::rename_with(.cols = "x",
.fn = ~paste0("new_", .x)))
expected output:
[[1]]
new_L1
1 1
2 2
3 3
4 1
5 2
6 3
[[2]]
new_L2
1 1
2 2
3 3
4 1
5 2
6 3