20

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, that is W[[1]] with W1 and so on, using a loop. How can I do?

Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
zaire90
  • 713
  • 2
  • 6
  • 11
  • Do you mean "I wish to create J new lists, from the elements from W, with new names as indicated" or do you mean "I wish to add names W1, W2 etc to the current list elements"? Note that the second will not change how you refer to the list elements, it will just add some ways that you can refer to them. – Glen_b Oct 22 '12 at 00:09

3 Answers3

21
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 = "")
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
  • Once I've renamed as you suggest me, can I acceded to the element's list writing W1, W2...or I've to write W[[1]] anyway? – zaire90 Oct 21 '12 at 12:26
  • @zaire90 You could access the list elements with `W$W1`, `W$W2` etc. Another way is to use the command `attach(W)`. Afterwards, all the elements can be accessed with `W1`, `W2` etc. But I recommend the first solution. – Sven Hohenstein Oct 21 '12 at 12:29
  • Just wanted to say `paste0` is a function in > R 2.15 (I think) and does the same thing as `paste` but with the default `sep = ""` – Tyler Rinker Oct 21 '12 at 13:25
  • The "best way to refer to the named elements is W[["W1"]]. I say best because it does not break inside functions as "$" access is prone to do and it generalizes nicely for constructing names to do the retrieval, for example `W[[ paste0("W", 1) ]]`. Try that with "$" and you will be disappointed (but wiser.) – IRTFM Oct 21 '12 at 15:49
15

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"
Quentin Geissmann
  • 2,240
  • 1
  • 21
  • 36
0

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"
user63230
  • 4,095
  • 21
  • 43