[R] Accumulating results from "for" loop in a list/array
Schalk Heunis
schalk.heunis at enerweb.co.za
Fri Sep 11 08:49:28 CEST 2009
Steven
I think list() can help you
##########################################
indlist = list()
for (i in 1:(dim(x)[2])) {
indlist[[paste("ind", i, sep = "")]] <- which(x[ , i] == "y")
}
accum = unlist(indlist)
print(indlist$ind1)
###########################################
Schalk Heunis
On Fri, Sep 11, 2009 at 7:52 AM, Steven Kang <stochastickang at gmail.com> wrote:
> 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)
> }
>
>> 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)
>
> Also, is there any way to extract individual objects ('ind1' etc) from
> 'accum'?
>
>> accum[1:length(ind1)]
> [1] 4 5 9 10
> gives 'ind1', but this may become messy for other objects (like 'ind10')
>
>
> Highly appreciate for sharing your expertise in solving this problem.
>
> [[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.
>
More information about the R-help
mailing list