用lapply替换所有空列表

ash*_*her 1 r lapply

我想用以下列表中的值0替换所有空列表(数字(0)):

a <- list(numeric(0), 3.13887804749505, c(0.745977548064631, 15.7233179232099, 
4.32068483740438, 19.6680377065919, 9.24007013740377), numeric(0), 
    c(28.8670111833615, 1.27199935252619, 26.6173612819351, 46.8824614685704
    ), c(3.03425142063166, 3.08366863855608, 4.37959434697201, 
    4.00518501422067, 2.05826729526789, 2.29413068424335))
Run Code Online (Sandbox Code Playgroud)

我在尝试这个:

b <- lapply(a, function(x) ifelse(length(x)==0,0,x))
Run Code Online (Sandbox Code Playgroud)

但我从每个列表中得到第一个数字:

list(0, 3.13887804749505, 0.745977548064631, 0, 28.8670111833615, 
    3.03425142063166)
Run Code Online (Sandbox Code Playgroud)

有没有办法用apply而不是循环来做到这一点?循环需要很长时间(列表非常大).

Ron*_*hah 5

我们可以使用lengths获取列表中每个元素的长度,然后用0替换零长度元素.

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

a
#[[1]]
#[1] 0

#[[2]]
#[1] 3.138878

#[[3]]
#[1]  0.7459775 15.7233179  4.3206848 19.6680377  9.2400701

#[[4]]
#[1] 0

#[[5]]
#[1] 28.867011  1.271999 26.617361 46.882461

#[[6]]
#[1] 3.034251 3.083669 4.379594 4.005185 2.058267 2.294131
Run Code Online (Sandbox Code Playgroud)