Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Replace values in nested list

Tags:

r

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.

like image 766
statespace Avatar asked Apr 03 '15 07:04

statespace


2 Answers

We can use stri_list2matrix

library(stringi)
m1 <- matrix(as.numeric(t(sapply(test, stri_list2matrix))), ncol=3)
m1
#    [,1] [,2] [,3]
#[1,]    1    2   NA
#[2,]   NA    2    3

This could be converted to data.frame

as.data.frame(m1)
like image 84
akrun Avatar answered Sep 18 '22 10:09

akrun


Following answers found here, here is a (bit twisted) way to go in base R:

data.frame(matrix(as.numeric(as.character(unlist(test, recursive=F))), nrow=length(test), byrow=T))

#  X1 X2 X3
#1  1  2 NA
#2 NA  2  3
like image 26
Cath Avatar answered Sep 21 '22 10:09

Cath