16

I'm trying to add elements to a list in a for loop. How can I set the field name?

L <- list() 
    for(i in 1:N)
    {
        # Create object Ps...
        string <- paste("element", i, sep="")
        L$get(string) <- Ps
    }

I want every element of the list to have the field name dependent from i (for example, the second element should have "element2")

How to do this? I think that my error is the usage of get

0

1 Answer 1

26

It seems like you're looking for a construct like the following:

N <- 3
x <- list()
for(i in 1:N) {
    Ps <- i  ## where i is whatever your Ps is
    x[[paste0("element", i)]] <- Ps
}
x
# $element1
# [1] 1
#
# $element2
# [1] 2
#
# $element3
# [1] 3

Although, if you know N beforehand, then it is better practice and more efficient to allocate x and then fill it rather than adding to the existing list.

N <- 3
x <- vector("list", N)
for(i in 1:N) {
    Ps <- i  ## where i is whatever your Ps is
    x[[i]] <- Ps
}
setNames(x, paste0("element", 1:N))
# $element1
# [1] 1
#
# $element2
# [1] 2
#
# $element3
# [1] 3
Sign up to request clarification or add additional context in comments.

2 Comments

Ok. I will do it. N is greater than 900, code will be more efficient
@HaddE.Nuff do you have any suggestions for the case were you don't know the size in advance. e.g., say the size is stochastic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.