Adding elements to a list in for loop in R

前端 未结 1 624
闹比i
闹比i 2020-12-08 23:59

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...
                


        
相关标签:
1条回答
  • 2020-12-09 00:32

    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
    
    0 讨论(0)
提交回复
热议问题