[R] Combine list element by column name to make a dataframe
Michael Hannon
jmhannon.ucdavis at gmail.com
Mon Apr 6 10:43:59 CEST 2015
Maybe something like the appended?
-- Mike
lst <- list(setNames(c(1,10,50,60,70,80),
c("id","id1","math","phy","che","bio")),
setNames(c(2,20,45),
c("id","id1","phy")),
setNames(c(3,30,75),
c("id","id1","bio")))
lst
df <- rbind(c(1,10,50,60,70,80),
c(2,20,NA,45,NA,NA),
c(3,30,NA,NA,NA,75))
colnames(df)<-c("id","id1","math","phy","che","bio")
row.names(df) <- NULL
df
allNames <- unique(unlist(lapply(lst, names)))
allNames
newLst <- lapply(lst, function(element) {
element[allNames]
})
newLst
df2 <- do.call(rbind, newLst)
df2
all.equal(df, df2)
On Sun, Apr 5, 2015 at 11:05 PM, Mohammad Tanvir Ahamed via R-help
<r-help at r-project.org> wrote:
> Hi ,
>
> I have a example list like follow
>
>
> ############################################
>
> lst<-list(setNames(c(1,10,50,60,70,80),c("id","id1","math","phy","che","bio")),setNames(c(2,20,45),c("id","id1","phy")),setNames(c(3,30,75),c("id","id1","bio")))
>
>
> My expected outcome :
>
> ---------------------------------------------------------------------
>
> df<-rbind(c(1,10,50,60,70,80),c(2,20,NA,45,NA,NA),c(3,30,NA,NA,NA,75))
>
> colnames(df)<-c("id","id1","math","phy","che","bio")
>
> row.names(df) <- NULL
>
> df
>
> ############################################
>
>
> Any suggestion will be appreciated .
>
> Thanks in advance.
>
>
>
> Best regards
>
>
> ...........................
>
> Tanvir Ahamed
>
> Göteborg, Sweden
>
>
>
>
> [[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.
More information about the R-help
mailing list