首页 > 解决方案 > 用 R 列表中的 0 替换 numeric(0)

问题描述

我有一个清单:

myList
$`0`
$`0`$item1
numeric(0)

$`0`$item2
[1] 350

$`0`$item3
numeric(0)


$`1`
$`1`$item1
numeric(0)

$`1`$item2
[1] 56

$`1`$item3
numeric(0)

我在这个列表中使用了一个 sapply 函数,但是得到一个错误:

参数的无效“类型”(列表)

我怎样才能将所有转换numeric(0)为 0,就像其他项目一样?

标签: rlistsapply

解决方案


假设您只有 1 个深度列表,这是最短的解决方案

my_list[lengths(my_list) == 0] <- 0

对于 2 深度列表

my_list <- lapply(my_list, function(x)x[lengths(x) == 0] <- 0)

推荐阅读