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?
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, ...)
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.
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 …
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With