[R] Accumulating results from "for" loop in a list/array

Johannes Hüsing johannes at huesing.name
Sat Sep 12 07:35:16 CEST 2009


Steven Kang schrieb:
> Dear R users,
>
>
> I would like to accumulate objects generated from 'for' loop to a list or
> array.
>
> To illustrate the problem, arbitrary data set and script is shown below,
>
>
> x <- data.frame(a = c(rep("n",3),rep("y",2),rep("n",3),rep("y",2)), b =
> c(rep("y",2),rep("n",4),rep("y",3),"n"), c = c(rep("n",7),rep("y",3)), d =
> c("y", rep("n",4), rep("y",2), rep("n",3)))
>
> for (i in 1:(dim(x)[2]))  {
>          assign(paste("ind", i, sep = ""), which(x[ , i] == "y"))
>           accum <- c(ind1, ind2, ind3, ind4)
> }
>
>   

Using "for" loops is not idiomatic; I tend to use them only if I really 
need intermediate results.

res <- apply(x, 2, function(answer) which(answer == "y"))

names(res) <- paste("ind", 1:ncol(x), sep="")

>> ind1
>>     
> [1]  4  5  9 10
>   
>> ind2
>>     
> [1] 1 2 7 8 9
>   
>> ind3
>>     
> [1]  8  9 10
>   
>> ind4
>>     
> [1] 1 6 7
>   
>> accum
>>     
>  [1]  4  5  9 10  1  2  7  8  9  8  9 10  1  6  7
>
> Are there any alternative method where the highlighted statement above can
> be represented without typing individual objects manually? (as it can be
> very tedious with large number of objects; i.e ind1, ind2, ....., ind100)
>
>   
/I think you are looking for unlist()./

> Also, is there any way to extract individual objects ('ind1' etc) from
> 'accum'?
>
>   
Well, I think they are not objects by themselves anymore. You may want 
to give the vector elements individual names based on their origin and 
then extract appropriate elements by string matching.




More information about the R-help mailing list