[R] Merge or combine data frames with missing columns
Charles C. Berry
cberry at tajo.ucsd.edu
Mon Dec 29 19:09:32 CET 2008
On Mon, 29 Dec 2008, Mark Heckmann wrote:
>
> Hi R-experts,
>
> suppose I have a list with containing data frame elements:
>
> [[1]]
> (Intercept) y1 y2 y3 y4
> -6.64 0.761 0.383 0.775 0.163
>
> [[2]]
> (Intercept) y2 y3
> -3.858 0.854 0.834
>
> Now I want to put them into ONE dataframe like this:
> (Intercept) y1 y2 y3 y4
> 1 -6.64 0.761 0.383 0.775 0.163
> 2 -3.858 NA 0.854 0.834 NA
>
> The problem I encounter is that not always all possible columns (Intercept, y1, y2, y3, y4) exist or at least have NA entries .
>
> I cannot figure out how (e.g. with merge)...
Just use a nested for loop:
> my.list <- list(c(a=1,b=2,c=3),c(a=10,b=20),c(g=7,h=8))
> dat <- data.frame()
> for(i in seq(along=my.list)) for(j in names(my.list[[i]])) dat[i,j] <- my.list[[i]][j]
If what you actually wanted was a _matrix_, and if it is rather large,
faster solutions might be possible using tapply or sapply.
HTH,
Chuck
>
> TIA, Mark
>
>
> --
> Mark Heckmann (Dipl. Wirt.-Ing.)
> phone +49 (0) 421/1614618
>
> Sensationsangebot verlängert: GMX FreeDSL - Telefonanschluss + DSL
> für nur 16,37 Euro/mtl.!* http://dsl.gmx.de/?ac=OM.AD.PD003K1308T4569a
>
> ______________________________________________
> 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.
>
Charles C. Berry (858) 534-2098
Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/ La Jolla, San Diego 92093-0901
More information about the R-help
mailing list