-2

I have the following list in R and I want to replace all NULL in the list with zero. Is there a better way of doing this rather than iterating through the list?

$`2014-06-15`
NULL
$`2014-06-16`
[1] 7
$`2014-06-17`
[1] 17
$`2014-06-18`
[1] 24
$`2014-06-19`
[1] 8
$`2014-06-20`
[1] 11
$`2014-06-21`
NULL
$`2014-06-22`
[1] 1
$`2014-06-23`
[1] 20
$`2014-06-24`
[1] 21
4

2 回答 2

1

参考您的解决方案,这种方式比用for循环和if语句替换更容易和更快。这是一个简短的例子。

> ( temp <- list(A = NULL, B = 1:5) )
# $A
# NULL
# 
# $B
# [1] 1 2 3 4 5

> temp[sapply(temp, is.null)] <- 0
> temp
# $A
# [1] 0
#
# $B
# [1] 1 2 3 4 5
于 2014-06-27T22:52:30.853 回答
0

没关系解决了。

temp 是我上面的日期列表

allDates <- names(temp)
for (i in allDates) {
  if (is.null(temp[[i]])) 
    temp[[i]] <- 0
}
于 2014-06-27T22:27:28.620 回答