I have a list of lists like this
list1 <- list(a = 1, error = 2)
list2 <- list(a = 1, error = 3)
mylist <- list(list1, list2)
I'd like to rename all the elements currently named "a" to the names in new_names
new_names <- c("new_1", "new_2")
I can do this with a for loop like so
for(i in seq_along(mylist)) {
names(mylist[[i]])[names(mylist[[i]]) == "a"] <- new_names[i]}
and get my desired result:
mylist
[[1]]
[[1]]$new_1
[1] 1
[[1]]$error
[1] 2
[[2]]
[[2]]$new_2
[1] 3
[[2]]$error
[1] 4
I'd like to do this without the for loop. Something like this map function perhaps, which doesn't work because it replaces all names, not just those that are "a".
library(purrr)
mylist_2 <- map(mylist, ~{names(.)[names(.) == "a"] <- new_names})