1

Here a list of list x generated as follow:

    list1 <- list(NULL, as.integer(0))
    list2 <- list(NULL, as.integer(1))
    list3 <- list(1:5, 0:4)
    x <- list(a=list1, b=list2, c=list3)

x has the following structure:

    str(x)
     List of 3
     $ a:List of 2
      ..$ : NULL
      ..$ : int 0
     $ b:List of 2
      ..$ : NULL
      ..$ : int 1
     $ c:List of 2
      ..$ : int [1:5] 1 2 3 4 5
      ..$ : int [1:5] 0 1 2 3 4

I'm trying to convert it to a coerced dataframe. I first used

   xc <- data.frame(lapply(x, as.numeric)

I got the following error

   Error in lapply(x, as.numeric) : 
     (list) object cannot be coerced to type 'double

Actually it only works with as.character as an argument.

My goal is to reach the dataframe with the following structure:

   str(xc)

   'data.frame':    2 obs. of  3 variables:
    $ a: int  NA 0 ...
    $ b: int  NA 1 ...
    $ c: int [1:5] 1 2 3 4 5 int [1:5] 0 1 2 3 4
BillyLeZeurbé
  • 57
  • 1
  • 10
  • Try `data.frame(lapply(x, unlist))` Please show a small reproducible example – akrun Jan 11 '17 at 16:30
  • Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE, : arguments imply different number of line : 1434, 1081, 5465, 95263, 18705, 6206, 12085, 22000, 499 – BillyLeZeurbé Jan 11 '17 at 16:34
  • Ok, please show a small reproducible example using `dput` as it is not clear about the structure of your data from the `str` alone for that big data – akrun Jan 11 '17 at 16:37
  • I've used do.call(rbind, x) to convert lists to a single data frame, but without an example I can't test it here. – Ryan Morton Jan 11 '17 at 16:37
  • You'll probably have to replace the `NULL` with `NA` prior to manipulating the list to prevent the resulting arrays being different lengths. – manotheshark Jan 11 '17 at 16:48
  • Try `x[sapply(x, is.null)] <- NA` - untested and borrowed from http://stackoverflow.com/questions/2991514/r-preventing-unlist-to-drop-null-values – manotheshark Jan 11 '17 at 16:58
  • I changed the way in which I have presented the problem. The problem is not coming from NA dear manotheshark – BillyLeZeurbé Jan 11 '17 at 17:45

1 Answers1

0

I think the columns of the resulting data frame must be lists (this is the type that can handle multiple vectors and NULL values).

Using dplyr or data.table package is probably the easiest way. You can then convert it back to base data.frame with as.data.frame:

library(data.table)
xc <- as.data.table(x)

or

library(dplyr)
xc <- as_data_frame(x)

After converting to base data.frame, the result is the same:

as.data.frame(xc)

#>      a    b             c
#> 1 NULL NULL 1, 2, 3, 4, 5
#> 2    0    1 0, 1, 2, 3, 4

The columns are lists:

str(as.data.frame(xc))

#> 'data.frame':    2 obs. of  3 variables:
#>  $ a:List of 2
#>   ..$ : NULL
#>   ..$ : int 0
#>  $ b:List of 2
#>   ..$ : NULL
#>   ..$ : int 1
#>  $ c:List of 2
#>   ..$ : int  1 2 3 4 5
#>   ..$ : int  0 1 2 3 4
bergant
  • 7,122
  • 1
  • 20
  • 24