[R] allocation/initialization of arrays/lists

Don MacQueen macq at llnl.gov
Mon Jul 6 21:41:16 CEST 2009


Initializing like this is generally recommended only when the object 
sizes get very big. Otherwise it's ok to grow your object as you go 
(i.e., append to it on each iteration).

When I want to initialize a list, I do this:

   array <- list()
   length(array) <- n

## then,
   for (i in 1:n) {
      ## do whatever
      array[[i]] <- {whatever you want in element i}
}

## initializing each element ahead of time is unlikely to be 
necessary. Don't even go there unless your loop is very slow.

## example
>  foo <- list() ; length(foo) <- 4
>
>  for (i in 1:4) foo[[i]] <- matrix(runif(6),ncol=3)
>  foo

## but it works just as well without setting the length ahead of time
>  foo <- list()
>  for (i in 1:4) foo[[i]] <- matrix(runif(6),ncol=3)
>  foo
[[1]]
            [,1]      [,2]       [,3]
[1,] 0.01916185 0.9891319 0.05098199
[2,] 0.26893225 0.6519368 0.14804408

[[2]]
           [,1]      [,2]      [,3]
[1,] 0.9022257 0.5747753 0.7262042
[2,] 0.1554868 0.5840976 0.9242820

[[3]]
           [,1]      [,2]       [,3]
[1,] 0.3265957 0.9435791 0.99473207
[2,] 0.7718667 0.8957601 0.04738975

[[4]]
           [,1]      [,2]      [,3]
[1,] 0.9570058 0.4994915 0.7615699
[2,] 0.5738325 0.6079360 0.2603755

-Don

At 12:58 PM -0500 7/5/09, zrl wrote:
>Dear list,
>
>I have a question regarding how to allocate or initialize the proper type of
>the arrays or lists.
>
>I have a for loop, each iteration, I want it to assign a subset of a data
>frame to an element of an array or list.
>However, I am wondering how I should initialize or allocate the empty array
>or list so that it has the same number of the elements as the subsets I am
>going to assign and also make the data type is compatible to the subset I am
>going to assign to it.
>It should look like this:
>
>#initialize or allocate.   ( I don't know how to)
>{ some codes: initialize an array or list (which one is better?) with "n"
>elements}
>
>#"for" loop for assigning a subset of a large data frame to the elements of
>the array or list (which on is better?)
>for (i in 1: n){
>array[i] <- df[df$V1==A[i],]
>}
>
>
>
>
>Thanks.
>
>ZRL
>
>	[[alternative HTML version deleted]]
>
>______________________________________________
>R-help at r-project.org mailing list
>https://*stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide http://*www.*R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.


-- 
--------------------------------------
Don MacQueen
Environmental Protection Department
Lawrence Livermore National Laboratory
Livermore, CA, USA
925-423-1062




More information about the R-help mailing list