Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename element's list indexed by a loop in R

Tags:

r

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?

like image 236
zaire90 Avatar asked Oct 21 '12 11:10

zaire90


People also ask

How to name elements of a list in R?

To name elements of an R List, access names of this list using names () function, and assign a vector of characters. In this tutorial, we will learn how to name elements of a list in R, using names () function, with the help of example programs. The syntax to assign names for elements in list myList is names(myList) <- c(name1, name2, ...)

How do you index a list in Python?

Indexing a List. In a list, components are always numbered. We can refer to the components using those in double square brackets. So, we can refer to list1’s components as list1 [ [1]], list1 [ [2]], etc.. If there are elements within a list’s components, then we can refer to them as list1 [ [1]] [1] and so on.

How do you create a list of elements in Python?

We can use the list () function to create a list. Another way to create a list is to use the c () function. The c () function coerces elements into the same type, so, if there is a list amongst the elements, then all elements are turned into components of a list. $ : num [1:12] 1 2 3 1 2 3 1 2 3 1 …

How to refer to an R List’s components in a similar fashion?

We can refer to an R list’s components in a similar fashion to vectors by using logical, integer or character vectors. How to Manipulate list in R? We can change existing components in a list.


2 Answers

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 = "")
like image 176
Sven Hohenstein Avatar answered Oct 21 '22 06:10

Sven Hohenstein


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"
like image 34
Quentin Geissmann Avatar answered Oct 21 '22 05:10

Quentin Geissmann