[R] Convert some columns of List to dataframe R

John McKown john.archie.mckown at gmail.com
Mon Aug 4 00:54:57 CEST 2014


On Sun, Aug 3, 2014 at 5:12 PM, Zilefac Elvis <zilefacelvis at yahoo.com> wrote:
> Dear All,
> I have a List in R and would like to convert it to data.frame.
> Below is a reproducible example. I can do something like:
>
> x1<-do.call(cbind.data.frame, lst3) #OR
> x1<-as.data.frame(lst3).
>
> However, my output looks like this:
>
> Year Site  x   Year Site  x
> 2001 G101 33.1 2001 G102 34
>
> I would like to have as my output:
>
> Year  G101   G102
> 2001  33.1   34
>
>
> Thanks
> Atem.
> ----------------------------------------------------------------------------------
>
>
>  list(structure(list(Year = 2001L, Site = structure(1L, .Label = "G101", class = "factor"),
>     x = 33.1), .Names = c("Year", "Site", "x"), row.names = c(NA,
> -1L), class = "data.frame"), structure(list(Year = 2001L, Site = structure(1L, .Label = "G102", class = "factor"),
>     x = 34), .Names = c("Year", "Site", "x"), row.names = c(NA,
> -1L), class = "data.frame"))
>


Try rbind_all in the dplyr package together with the dcast() function
in the reshpae2 package

output1 <- rbind_all(as.list(lst3));
realOutput <- dcast(output1, Year ~ Site, value.var="x");

Example transcript:

> lst3 <- list(structure(list(Year = 2001L, Site = structure(1L, .Label = "G101", class = "factor"),
+     x = 33.1), .Names = c("Year", "Site", "x"), row.names = c(NA,
+ -1L), class = "data.frame"), structure(list(Year = 2001L, Site =
structure(1L, .Label = "G102", class = "factor"),
+     x = 34), .Names = c("Year", "Site", "x"), row.names = c(NA,
+ -1L), class = "data.frame"))
> library(dplyr);
> rbind_all(lst3);
  Year Site    x
1 2001 G101 33.1
2 2001 G102 34.0
Warning message:
In rbind_all(lst3) : Unequal factor levels: coercing to character
> dcast(output1,Year ~ Site,value.var="x")
  Year G101 G102
1 2001 33.1   34
>


Sorry for the extra reply.  60 hour work weeks and 61 years of age
don't mix well. Back to watching Beakman on Netflix.


-- 
There is nothing more pleasant than traveling and meeting new people!
Genghis Khan

Maranatha! <><
John McKown



More information about the R-help mailing list