[R] Retrieving data frames from a for loop

jim holtman jholtman at gmail.com
Fri Feb 15 03:42:20 CET 2008


Use a 'list' to capture the data within the loop:

> result <- vector('list', 20)  # preallocate
> tab <- data.frame(x=1:20)
> for (i in 1:20) {
+
+     g<-sample(rep(LETTERS[1:2],each=10))
+     result[[i]] <-data.frame(tab,g)
+
+ }
> # you can now access the combinations like this:
> result[[1]]
    x g
1   1 B
2   2 A
3   3 B
4   4 B
5   5 B
6   6 B
7   7 A
8   8 B
9   9 A
10 10 B
11 11 A
12 12 B
13 13 B
14 14 A
15 15 A
16 16 A
17 17 A
18 18 B
19 19 A
20 20 A
> result[[5]]
    x g
1   1 B
2   2 A
3   3 B
4   4 B
5   5 A
6   6 A
7   7 B
8   8 A
9   9 B
10 10 A
11 11 B
12 12 A
13 13 B
14 14 B
15 15 B
16 16 A
17 17 A
18 18 A
19 19 A
20 20 B
>
>


On Thu, Feb 14, 2008 at 6:42 PM, Judith Flores <juryef at yahoo.com> wrote:
> Dear R-helpers,
>
>   I need to retrieve the data frames generated in a
> for loop. What I have looks something like this:
>
> where tab is a pre-existing data frame.
>
> for (i in 1:20) {
>
>     g<-sample(rep(LETTERS[1:2],each=10))
>     combination<-data.frame(tab,g)
>
> }
>
>   I tried to name every single combination doing
> this:
>
> assign(paste('combination',i), combination)
>
>  without success.
>
> I need to retrieve every combination per separate.
>
> Thank you once again for your help.
>
>
>      ____________________________________________________________________________________
> Looking for last minute shopping deals?
>
> ______________________________________________
> 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.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?



More information about the R-help mailing list