简体   繁体   中英

Change name of element names in loop through lists

Is there a way to change the names of the elements of multiple lists in a loop:

a <- list(1, 2)
b <- list(3, 4)
for (my.list in c("a", "b") {
  names(my.list) <- c("element1", "element2")
}

In my own words, I would say the problem is, that the variable my.list needs to be evaluated to the name of the list. Therefore, I tried assign(names(my.list) <- ... as well as names(as.name(my.list)) <- ... , but to no success.

Try this:

a <- list(1, 2)
b <- list(3, 4)

for (my.list in c("a", "b")) {
  x <- get(my.list)
  names(x) <- c("element1", "element2")
  assign(my.list, x)
}

We could also use the names<- to assign

for(my.list in c("a", "b")) {
  assign(my.list, `names<-`(get(my.list), c("element1", "element2")))
}

a
#$element1
#[1] 1

#$element2
#[1] 2

b
#$element1
#[1] 3

#$element2
#[1] 4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM