Search code examples
rlistdataframe

Different length listed format to R Dataframe


I am using CountsEPPM to do some sample problems. This package use data as listed format.

library(CountsEPPM)
data("herons.group")
herons.group
$group
[1]  Adult     Immature
Levels:  Adult  Immature

$number.attempts
$number.attempts[[1]]
 [1] 0 5 2 1 1 1 0 2 0 1 0 1 0 0 2 1 0 1 0 0 1 0 0 0 1

$number.attempts[[2]]
 [1] 0 2 2 1 5 1 2 2 1 1 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 1

I am using the following code to convert the listed format to dataframe. It ended up with an error.

do.call("rbind", lapply(herons.group, as.data.frame))
Error in data.frame(c(0, 5, 2, 1, 1, 1, 0, 2, 0, 1, 0, 1, 0, 0, 2, 1,  : 
  arguments imply differing number of rows: 25, 26

The head of the dataframe would be like:

  group number.attempts
1 Adult               0
2 Adult               5
3 Adult               2
4 Adult               1
5 Adult               1
6 Adult               1

The tail:

      group number.attempts
46 Immature               0
47 Immature               0
48 Immature               0
49 Immature               0
50 Immature               0
51 Immature               1

Solution

  • Assuming that I understood the structure of the data:

    data.frame(group = rep(herons.group$group, times = lengths(herons.group$number.attempts)),
               number.attempts = unlist(herons.group$number.attempts))