I\'m new on R language and I still have a lot to learn.
I\'ve a list W
of J elements and I would like to rename its elements W[[i]]
with Wi
names(W) <- paste0("W", seq_along(W))
should do the trick.
Note that paste0
was introduced in R 2.15 as a "slightly more efficient" version of paste(..., sep = "", collapse)
. If you are using an earlier version of R, you can achieve the same using paste
:
names(W) <- paste("W", seq_along(W), sep = "")
Alternatively you can use sprintf()
:
w<-list(a="give",b="me an",c="example")
names(w)<-sprintf("W%i",1:length(w))
As you can see, you do not need a loop for this.
It should do the work. In this example, the names are W1,W2 and W3
print(w)
$W1
[1] "give"
$W2
[1] "me an"
$W3
[1] "example"
A purrr
solution using @Quentin's data:
library(purrr)
w <- list(a = "give", b = "me an", c = "example") %>%
set_names(~paste0("W", 1:length(w)))
w
# $W1
# [1] "give"
# $W2
# [1] "me an"
# $W3
# [1] "example"