将 R 列表中的 numeric(0) 替换为 0

问题描述 投票:0回答:4

我有一个清单:

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,就像其他项目一样?

r list sapply
4个回答
3
投票

如果深度未知或不相等,您可以使用递归函数:

f <- function(x) {
  if(is.list(x)) lapply(x, f)
  else ifelse(length(x) == 0, 0, x)
}

f(myList)
#$`0`
#$`0`$item1
#[1] 0
#
#$`0`$item2
#[1] 350
#
#$`0`$item3
#[1] 0
#
#
#$`1`
#$`1`$item1
#[1] 0
#
#$`1`$item2
#[1] 56
#
#$`1`$item3
#[1] 0
#
#
#$`2`
#[1] 4
#
#$`3`
#[1] 0

另一种选择是使用

rapply

rapply(myList, \(x) {if(length(x)==0) 0 else x}, how="replace")

数据:

myList <- list(`0` = list(item1 = numeric(0), item2 = 350, item3 = numeric(0)),
               `1` = list(item1 = numeric(0), item2 = 56, item3 = numeric(0)),
               `2` = 4, `3` = numeric(0))

2
投票

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

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

对于 2 深度列表

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

0
投票

使用
purrr
modify()

newList <- purrr::modify(myList, ~ if(length(.) == 0){ 
                                   0 
                                   } else { . })

或使用
base::lapply

newList <- lapply(myList, function(x){
if(length(x) == 0){
out <- 0
} else {
out <- x
}
return(out)
})

0
投票

使用嵌套

lapply

lapply(my_list, function(x) lapply(x, function(x) ifelse(length(x) == 0, 0, x)))
$`0`
$`0`$item1
[1] 0

$`0`$item2
[1] 350

$`0`$item3
[1] 0


$`1`
$`1`$item1
[1] 0

$`1`$item2
[1] 56

$`1`$item3
[1] 0

sapply
里面
lapply

lapply(my_list, function(x) sapply(x, function(x) ifelse(length(x) == 0, 0, x)))

$`0`
item1 item2 item3 
    0   350     0 

$`1`
item1 item2 item3 
    0    56     0 

或在内部和外部使用

sapply

sapply(my_list, function(x) sapply(x, function(x) ifelse(length(x) == 0, 0, x)))

        0  1
item1   0  0
item2 350 56
item3   0  0

在名单上

my_list <- list(`0` = list(item1 = numeric(0), item2 = 350, item3 = numeric(0)),
                `1` = list(item1 = numeric(0), item2 = 56, item3 = numeric(0)))
© www.soinside.com 2019 - 2024. All rights reserved.