Reputation: 987
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.
Upvotes: 1
Views: 445
Reputation: 886948
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
Upvotes: 0
Reputation: 56004
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)
}
Upvotes: 3