[R] allocation/initialization of arrays/lists
David Winsemius
dwinsemius at comcast.net
Sun Jul 5 21:01:48 CEST 2009
On Jul 5, 2009, at 2:43 PM, Martin Morgan wrote:
> Hi ZRL,
>
> 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],]
>> }
>
> You could let the software figure it out for you
>
> result = sapply(1:n, function(i, df, A) {
> df[df$V1==A[i],]
> }, df=df, A=A)
>
> or better (because you don't have to ensure that n is the length of A)
> if A is a vector
>
> result = sapply(A, function(a, df) {
> df[df$V1 == a, ]
> }, df=df)
Or even:
result <- subset(df, V1 %in% A)
... possibly needing some ordering.
David Winsemius, MD
Heritage Laboratories
West Hartford, CT
More information about the R-help
mailing list