我经常遇到这样的数据 struct :
employees <- list(
list(id = 1,
dept = "IT",
age = 29,
sportsteam = "softball"),
list(id = 2,
dept = "IT",
age = 30,
sportsteam = NULL),
list(id = 3,
dept = "IT",
age = 29,
sportsteam = "hockey"),
list(id = 4,
dept = NULL,
age = 29,
sportsteam = "softball"))
在许多情况下,这样的列表可能长达数千万项,因此内存问题和效率始终是一个问题.
我想将列表转换为数据帧,但如果我运行:
library(data.table)
employee.df <- rbindlist(employees)
我会因为空值而出错.我通常的策略是使用如下函数:
nullToNA <- function(x) {
x[sapply(x, is.null)] <- NA
return(x)
}
然后:
employees <- lapply(employees, nullToNA)
employee.df <- rbindlist(employees)
它回来了
id dept age sportsteam
1: 1 IT 29 softball
2: 2 IT 30 NA
3: 3 IT 29 hockey
4: 4 NA 29 softball
然而,当应用于1000万个 case 时,nullToNA函数非常慢,因此如果有更有效的方法,那就更好了.
有一点似乎减缓了这个过程,那就是.null函数一次只能应用于一个项目(与is.na不同,is.na可以一次扫描完整列表).
关于如何在大型数据集上高效地执行此操作,有什么建议吗?