preallocate list in R

前端 未结 3 941
渐次进展
渐次进展 2020-12-04 23:45

It is inefficient in R to expand a data structure in a loop. How do I preallocate a list of a certain size? matrix makes this easy via the n

相关标签:
3条回答
  • 2020-12-05 00:04

    vector can create empty vector of the desired mode and length.

    x <- vector(mode = "list", length = 10)
    
    0 讨论(0)
  • 2020-12-05 00:10

    To expand on what @Jilber said, lapply is specially built for this type of operation.

    instead of the for loop, you could use:

    x <- lapply(1:10, function(i) i)
    

    You can extend this to more complicated examples. Often, what is in the body of the for loop can be directly translated to a function which accepts a single row that looks like a row from each iteration of the loop.

    0 讨论(0)
  • 2020-12-05 00:21

    Something like this:

       x <- vector('list', 10)
    

    But using lapply is the best choice

    0 讨论(0)
提交回复
热议问题