I have multiple list with the same amount of items. I want to rename all lists items in loop. For example from lists items names "a, b, c", I want to rename them to "first, second, third":
#create 3 lists with items names a, b, c
list1 <- list(a=c(1:10), b=c(1:5), c=c(1:3))
list2 <- list(a="a", b="b", c="c")
list3 <- list(a=runif(4), b=runif(2), c=runif(4))
# wanted names of list items
names <- c("first", "second", "third")
new_list <- list()
for (i in 1:3){
for(j in seq_along(names)) {
n <- paste0(names[[j]])
new_list[[n]] <- assign(paste0("list_", i), get(paste0("list", i)))
}
}
But the result rename only third list.. How should I rename all lists items at once?
We can use lapply()
and setNames()
:
lapply(list(list1, list2, list3), \(x) setNames(x, names))
#> [[1]]
#> [[1]]$first
#> [1] 1 2 3 4 5 6 7 8 9 10
#>
#> [[1]]$second
#> [1] 1 2 3 4 5
#>
#> [[1]]$third
#> [1] 1 2 3
#>
#>
#> [[2]]
#> [[2]]$first
#> [1] "a"
#>
#> [[2]]$second
#> [1] "b"
#>
#> [[2]]$third
#> [1] "c"
#>
#>
#> [[3]]
#> [[3]]$first
#> [1] 0.7475211 0.9317233 0.1603680 0.7952381
#>
#> [[3]]$second
#> [1] 0.5450439 0.8351545
#>
#> [[3]]$third
#> [1] 0.1782355 0.9909339 0.2366660 0.7104271
Created on 2023-03-07 by the reprex package (v2.0.1)
Data from OP
list1 <- list(a=c(1:10), b=c(1:5), c=c(1:3))
list2 <- list(a="a", b="b", c="c")
list3 <- list(a=runif(4), b=runif(2), c=runif(4))
names <- c("first", "second", "third")
We could also use a for
loop with setNames)()
:
new_list <- list()
for (i in 1:3){
new_list[[i]] <- setNames(get(paste0("list", i)), names)
}
Created on 2023-03-07 by the reprex package (v2.0.1)