[R] merging dataframes in a list

MacQueen, Don macqueen1 at llnl.gov
Mon Jun 6 18:34:26 CEST 2016


I would probably do it this way,

tmp <- list(data.frame(name="sample1", red=20),
            data.frame(name="sample1", green=15),
            data.frame(name="sample2", red=10),
            data.frame(name="sample2", green=30))

fun1 <- function(df) data.frame(name=df$name, color=names(df)[2],
value=df[[2]])

tmp1 <- lapply(tmp,fun1)

tmp2 <- do.call(rbind,tmp1)

tmp3 <- reshape(tmp2, idvar='name', timevar='color', direction='wide')

This does the job, except for the extraneous "value." [and they can easily
be removed using gsub()].

Whether or not it will work for a more general case, I don't know.

-Don


-- 
Don MacQueen

Lawrence Livermore National Laboratory
7000 East Ave., L-627
Livermore, CA 94550
925-423-1062





On 6/3/16, 11:20 AM, "R-help on behalf of Ed Siefker"
<r-help-bounces at r-project.org on behalf of ebs15242 at gmail.com> wrote:

>I have a list of data as follows.
>
>> list(data.frame(name="sample1", red=20), data.frame(name="sample1",
>>green=15), data.frame(name="sample2", red=10), data.frame(name="sample
>>2", green=30))
>[[1]]
>     name red
>1 sample1  20
>
>[[2]]
>     name green
>1 sample1    15
>
>[[3]]
>     name red
>1 sample2  10
>
>[[4]]
>     name green
>1 sample2    30
>
>
>I would like to massage this into a data frame like this:
>
>     name red green
>1 sample1  20    15
>2 sample2  10    30
>
>
>I'm imagining I can use aggregate(mylist, by=samplenames, merge)
>right?  But how do I get the list of samplenames?  How do I subset
>each dataframe inside the list?
>
>______________________________________________
>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