[R] building a list in a loop
William Dunlap
wdunlap at tibco.com
Fri Jun 5 16:57:08 CEST 2015
Does the following do what you want?
> d <- list() # empty list
> for(i in 1:8) if (i %% 2 == 0) {
newElement <- structure(list(i), names=LETTERS[i])
d <- c(d, newElement)
}
> str(d)
List of 4
$ B: int 2
$ D: int 4
$ F: int 6
$ H: int 8
Bill Dunlap
TIBCO Software
wdunlap tibco.com
On Fri, Jun 5, 2015 at 1:40 AM, 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.
[[alternative HTML version deleted]]
More information about the R-help
mailing list