renkun-ken / rlist

A Toolbox for Non-Tabular Data Manipulation
Other
204 stars 28 forks source link

A new function to convert list with different length vectors to data.frame #111

Open zhilongjia opened 9 years ago

zhilongjia commented 9 years ago

Here is an enhancement.

aa <- list(A=c(1, 3, 4), B=c(3,5,7,7,8))

results in a data.frame:

A B
1 3
3 5
4 7
NA 7
NA 8
renkun-ken commented 8 years ago

Would you please provide some use cases that make this enhancement particularly useful?

zhilongjia commented 8 years ago

it's not easy to write such kind of list into files so far. The enhancement will make it. Or just a function to write the unequal list into file.

renkun-ken commented 8 years ago

The following code should work:

test <- function(x, ..., stringsAsFactors = FALSE) {
  max_len <- max(vapply(x, length, integer(1L)))
  data.frame(lapply(x, function(v) {
    length(v) <- max_len
    v
  }), stringsAsFactors = stringsAsFactors, ...)
}
> test(list(a = c(1,2,3), b = c(1,2,3,4,5,6)))
   a b
1  1 1
2  2 2
3  3 3
4 NA 4
5 NA 5
6 NA 6

Not sure yet whether to add this function to the package.

zhilongjia commented 8 years ago

Here is a reference: SO.

I believe the function is related with rlist package and helpful in the situation mentioned above.