Adela
Adela

Reputation: 1797

Names of vectors in list

I have list of vectors of same length and I'm looking for some easy way how to name elements of the vectors. I can do it by using for-loop like this:

myList <- list(c(1,2,3), c(4,5,6), c(7,8,9))
for (i in 1:3){ names(myList[[i]]) <- c("a", "b", "c") }

Is there any way to do this e.g. with lapply or another more elegant way?

I tried it with this code:

lapply(names(myList), function(i) names(myList[[i]])<- c("a", "b", "c"))

But this one only gives me new list of names, not names my current list.

Upvotes: 3

Views: 142

Answers (2)

akrun
akrun

Reputation: 887158

We can try

lapply(myList, setNames, letters[1:3])

Upvotes: 2

Vadym B.
Vadym B.

Reputation: 681

You can try this:

lapply(myList, function(x) { names(x) <- c('a', 'b', 'c'); x})

Upvotes: 1

Related Questions