Assume we have a nested list:
test <- list(
list(a = 1, b = 2, c = NULL),
list(a = NULL, b = 2, c = 3))
How do I replace all NULL
values with, say, NA
to preserve the structure of data? So that I don't end up losing values/structure when I try to make data frame out of the list. Such as:
data.frame(matrix(unlist(test), nrow = 2, byrow = T))
X1 X2
1 1 2
2 2 3
Desired output is something like:
X1 X2 X3
1 1 2 NA
2 NA 2 3
There are suggestions to do it this way:
rbind.fill(lapply(test, function(f) {
as.data.frame(Filter(Negate(is.null), f))
}))
Which is not quite as vectorized as I'd like. Obviously size and performance is an issue. One workaround that pops in mind is replacing all NULL values similarly as it can be done for the whole data frame at once. And then unlist()
and matrix()
the list.
I'm not sure about the gain in the performance (if there is any at all). Perhaps good old lapply()
isn't all that bad.