[R] how to stack a list of arrays

R. Michael Weylandt michael.weylandt at gmail.com
Thu Nov 24 05:59:22 CET 2011


Try this for the given data: you'll have to modify the group label
trick a bit if row-numbers aren't even for each element of L, but it's
not hard.

L <- list(`0` = matrix(rnorm(6), ncol = 2), `1` = matrix(rnorm(6),
ncol = 2), `2` = matrix(rnorm(6), ncol = 2))
# Generally it's bad form to use numbers for names

cbind(do.call(rbind, L), group = rep(as.double(names(L)), each = nrow(L[[1]]))

Good luck,
Michael

2011/11/23 Ernest Adrogué <nfdisco at gmail.com>:
> Hello,
>
> I have this list of 2-d arrays:
>
> $`0`
>             k        d
> [1,] 0.2011962 4.019537
> [2,] 0.2020706 5.722719
> [3,] 0.2029451 7.959612
>
> $`1`
>             k        d
> [1,] 0.3148325 2.606903
> [2,] 0.3160287 3.806665
> [3,] 0.3172249 5.419222
>
> $`2`
>             k        d
> [1,] 0.2332536 4.949390
> [2,] 0.2342188 7.115258
> [3,] 0.2351840 9.955909
>
> which I need to transform into a data frame like this one:
>
>             k        d group
> [1,] 0.2011962 4.019537     0
> [2,] 0.2020706 5.722719     0
> [3,] 0.2029451 7.959612     0
> [1,] 0.3148325 2.606903     1
> [2,] 0.3160287 3.806665     1
> [3,] 0.3172249 5.419222     1
> [1,] 0.2332536 4.949390     2
> [2,] 0.2342188 7.115258     2
> [3,] 0.2351840 9.955909     2
>
> Is there any R function that I can use? I know stack() but it only
> works with vectors.
>
> Thank you!
> Ernest
>
> ______________________________________________
> 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