[R] merge list entries

jim holtman jholtman at gmail.com
Tue Aug 23 22:21:14 CEST 2005


Try:

> newL <- do.call('rbind', lapply(1:length(myl), function(x){
+     cbind(myl[[x]], q=x)
+ }))
> 
> 
> reshape(newL, v.names='grade', idvar='id', timevar='q', direction='wide')
      id grade.1 grade.2 grade.3
1  Alice      90      70      NA
2    Bob      49      NA      84
21 Chuck      NA      93      40
> newL
      id grade q
1  Alice    90 1
2    Bob    49 1
11 Alice    70 2
21 Chuck    93 2
12   Bob    84 3
22 Chuck    40 3

On 8/23/05, alejandro munoz <guerinche at gmail.com> wrote:
> dear expeRts,
> 
> i would like to merge the data frame entries in a list. for example:
> 
> > #input
> > myl <- list(q1=data.frame(id=c("Alice", "Bob"), grade=c(90, 49)),
>              q2=data.frame(id=c("Alice", "Chuck"), grade=c(70, 93)),
>              q3=data.frame(id=c("Bob", "Chuck"), grade=c(84, 40)))
> > #output
> > (mydf <- magic(myl))
>      id grade.1 grade.2 grade.3
> 1 Alice      90      70      NA
> 2   Bob      49      NA      84
> 3 Chuck      NA      93      40
> 
> my three attempts, and their error messages, follow:
> > lapply(myl, merge, by="id", all=TRUE)
> Error in as.data.frame(y) : argument "y" is missing, with no default
> 
> > lapply(myl[[-1]], merge, y=myl[[1]], by="id", all=TRUE)
> Error in lapply(myl[[-1]], merge, y = myl[[1]], by = "id", all = TRUE) :
>        attempt to select more than one element
> 
> > do.call("merge", list(myl[[1]], myl[[-1]], by="id", all=TRUE))
> Error in do.call("merge", list(myl[[1]], myl[[-1]], by = "id", all = TRUE)) :
>        attempt to select more than one element
> 
> i can do the merge sequentially, e.g.
> m12 <- merge(myl[[1]], myl[[2]], ...)
> m123 <- merge(m12, myl[[3]], ...)
> but (a) in my actual example i have up to q7, and (b) this looks very
> clumsy, even if i wrapped it inside a do loop.
> 
> i'd appreciate any help.
> 
> alejandro
> 
> ______________________________________________
> 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
> 


-- 
Jim Holtman
Convergys
+1 513 723 2929

What the problem you are trying to solve?




More information about the R-help mailing list