[R] List to dataframe

jim holtman jholtman at gmail.com
Wed Feb 8 16:28:16 CET 2012


Does this do what you want:

> list <- list(A=1:4, B=1:6, C=1:9)
> result <- lapply(names(list), function(x){
+     data.frame(name = x
+         , length = length(list[[x]])
+         , gt5 = sum(list[[x]] > 5)
+         , lt5 = sum(list[[x]] < 5)
+         )
+ })
> do.call(rbind, result)
  name length gt5 lt5
1    A      4   0   4
2    B      6   1   4
3    C      9   4   4

On Wed, Feb 8, 2012 at 10:18 AM, Johannes Radinger <JRadinger at gmx.at> wrote:
> Hi,
>
>> Try
>>
>> list <- list(1:4, 1:6, 1:9)
>> t(sapply(list, function(x) c(length(x), sum(x > 5), sum(x < 5))))
>>
>
> thank you...the sapply approach seems straight forward, although I don't get the names into an own column... When the list elements are named the name is used for the rownames. I'd like to have them as an own column and no row names...
>
> like for the list:
> list <- list(A=1:4, B=1:6, C=1:9)
> t(sapply(list, function(x) c(length(x), sum(x > 5), sum(x < 5))))
>
> /Johannes
>
>> HTH,
>> Jorge.-
>>
>>
>> On Wed, Feb 8, 2012 at 8:50 AM, Johannes Radinger <> wrote:
>>
>> > Hi,
>> > I want to "melt" my list and get certain deskriptive factors (length of
>> a
>> > vector etc.) into a dataframe. Best to describe it with an example:
>> >
>> > A <- seq(4)
>> > B <- seq(6)
>> > C <- seq(9)
>> >
>> > ls <- list(A,B,C) # this is my list with vectors of different length
>> >
>> > # thats the dataframe how it should look like:
>> > name    length(x)       length(x[x>5])  length(x[x<5])
>> > A       4       0       4
>> > B       6       1       4
>> > C       9       4       4
>> >
>> > How can that be achieved?
>> >
>> >
>> > /johannes
>> > --
>> >
>> > ______________________________________________
>> > 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.
>> >
>
> --
>
> ______________________________________________
> 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.



-- 
Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?
Tell me what you want to do, not how you want to do it.



More information about the R-help mailing list