首页 > 解决方案 > Rename portions of named list of lists without for loop

问题描述

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})

标签: rpurrr

解决方案


You can use Map from baseR

f <- function(x, y) {
  names(x)[names(x) == "a"] <- y
  x
}

Map(f, x = mylist, y = new_names)
#[[1]]
#[[1]]$new_1
#[1] 1
#
#[[1]]$error
#[1] 2
#
#
#[[2]]
#[[2]]$new_2
#[1] 1
#
#[[2]]$error
#[1] 3

Using purrr it would be map2

purrr::map2(mylist, new_names, f)

推荐阅读