[R] writing elements in list as a data frame
jim holtman
jholtman at gmail.com
Thu Sep 6 00:01:37 CEST 2007
Try this:
> sls <- list(a=matrix(sample(10), ncol=2, dimnames=list(NULL, c('x', 'y'))),
+ b=matrix(sample(16), ncol=2, dimnames=list(NULL, c('x', 'y'))))
> sls
$a
x y
[1,] 8 2
[2,] 9 10
[3,] 4 1
[4,] 5 7
[5,] 3 6
$b
x y
[1,] 4 14
[2,] 3 15
[3,] 16 5
[4,] 1 9
[5,] 8 7
[6,] 10 2
[7,] 12 13
[8,] 11 6
> # create output matrix
> do.call('rbind', lapply(names(sls), function(.name){
+ data.frame(sls[[.name]], Name=.name)
+ }))
x y Name
1 8 2 a
2 9 10 a
3 4 1 a
4 5 7 a
5 3 6 a
6 4 14 b
7 3 15 b
8 16 5 b
9 1 9 b
10 8 7 b
11 10 2 b
12 12 13 b
13 11 6 b
>
>
On 9/5/07, Srinivas Iyyer <srini_iyyer_bio at yahoo.com> wrote:
> Dear R-helpers,
> Lists in R are stumbling block for me.
>
> I kindly ask you to help me able to write a
> data-frame.
>
> I have a list of lists.
>
> > sls[1:2]
> $Andromeda_maya1
> x y
> [1,] 369 103
> [2,] 382 265
> [3,] 317 471
> [4,] 169 465
> [5,] 577 333
>
> $Andromeda_maya2
> x y
> [1,] 173 507
> [2,] 540 395
> [3,] 268 143
> [4,] 346 175
> [5,] 489 91
>
> I want to be able to write a data.frame like the
> following:
> X Y Name
> 369 103 Andromeda_maya1
> 382 265 Andromeda_maya1
> 317 471 Andromeda_maya1
> 169 465 Andromeda_maya1
> 577 333 Andromeda_maya1
> 173 507 Andromeda_maya2
> 540 395 Andromeda_maya2
> 268 143 Andromeda_maya2
> 346 175 Andromeda_maya2
> 489 91 Andromeda_maya2
>
> Is there a way to convert this list-of-list into a
> data.frame.
>
> Thanks
> srini
>
> ______________________________________________
> R-help at stat.math.ethz.ch 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