[R] building a list in a loop

Jeff Newmiller jdnewmil at dcn.davis.CA.us
Fri Jun 5 16:27:35 CEST 2015


Your explanation of the problem is unclear and your use of HTML formatting corrupts your code examples.

One issue is your reference to a loop while showing no loop nor input nor output. There is more than one construct for iterating in R. One problem you may be encountering is that you cannot change the vector over which you iterate in a for loop while you are in that loop. If that is your problem then you probably need to use something like a while loop. However your example is too abstract (and scrambled by HTML) for me to fix it.

To make your problem clearer [1], you could give us a dput of a sample input data object with a few elements (rows, columns, whatever) and build each element of your output without resorting to a loop. We could then suggest ways to use a loop to accomplish the same thing.

[1] http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example
---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                      Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k
--------------------------------------------------------------------------- 
Sent from my phone. Please excuse my brevity.

On June 5, 2015 1:40:04 AM PDT, carol white via R-help <r-help at r-project.org> wrote:
>It might be an easy question but how to construct correctly a list in a
>loop? 
>
>The following doesn't work
>before starting the loopd = NULL#in the loop, 1st iteration
>d = list(d,c(1,2,3)d[[1]]
>NULL
>
>[[2]]
>[1] 1 2 3#in the loop, 2nd iterationd=list(d,c(4,5,6)d
>[[1]]
>[[1]][[1]]
>NULL
>
>[[1]][[2]]
>[1] 1 2 3
>
>
>[[2]]
>[1] 4 5 6
>the goal is to have the result of d= list(c(1,2,3),c(4,5,6)) where the
>list components are not known out of the loop.
>d[[1]]
>[1] 1 2 3
>
>[[2]]
>[1] 4 5 6
>Moreover, how to name the components of the list in the loop while
>constructing as the names are not known out of the loop, either? note
>that the name of the component is stored in a variable in the loop
>
>d = NULL#name1 contains the name for c(1,2,3), how to give the name
>below?
>d = list(d,c(1,2,3)
>Thanks
> 
>	[[alternative HTML version deleted]]
>
>______________________________________________
>R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>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