相关疑难解决方法(0)

是否有更有效的方法在列表中用NA替换NULL?

我经常遇到这样的结构数据:

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"))
Run Code Online (Sandbox Code Playgroud)

在许多情况下,此类列表可能长达数千万个项目,因此内存问题和效率始终是一个问题.

我想将列表转换为数据帧,但如果我运行:

library(data.table)
employee.df <- rbindlist(employees)
Run Code Online (Sandbox Code Playgroud)

由于NULL值,我得到错误.我的正常策略是使用如下函数:

nullToNA <- function(x) {
    x[sapply(x, is.null)] <- NA
    return(x)
}
Run Code Online (Sandbox Code Playgroud)

然后:

employees <- lapply(employees, nullToNA)
employee.df <- rbindlist(employees)
Run Code Online (Sandbox Code Playgroud)

返回

   id dept …
Run Code Online (Sandbox Code Playgroud)

performance null r list

32
推荐指数
3
解决办法
2万
查看次数

标签 统计

list ×1

null ×1

performance ×1

r ×1