[R] List to data frame

Joshua Wiley jwiley.psych at gmail.com
Mon Jul 26 17:06:37 CEST 2010


Hi,

Here is another option if you already have a list you want to convert.
 This will handle different elements of the list being different
lengths.

#Using your example data
mydata <- list(c(1,2,3),c(4,5,6))

data.frame(
 OriginalListIndex = rep(x = seq_along(mydata),
   times = unlist(lapply(mydata, length))),
 Item = unlist(mydata)
)

#Just to demonstrate that this method works generally
mydata <- list(c(1,2,3), c(7,6), c(3,4,5,6,7,8,9))

data.frame(
 OriginalListIndex = rep(x = seq_along(mydata),
   times = unlist(lapply(mydata, length))),
 Item = unlist(mydata)
)


HTH,

Josh

On Mon, Jul 26, 2010 at 7:46 AM, Johannes Graumann
<johannes_graumann at web.de> wrote:
> Hi,
>
> Any ideas on how to efficiently convert
>
>> list(c(1,2,3),c(4,5,6))
>
> to
>
>> data.frame(OriginalListIndex=c(1,1,1,2,2,2),Item=c(1,2,3,4,5,6))
>
> Thanks for any hints,
>
> Joh
>
> ______________________________________________
> 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.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/



More information about the R-help mailing list