使用 dplyr 对多列求和时忽略 NA

Ignoring NA when summing multiple columns with dplyr

我正在对多个列进行求和,其中一些具有 NA。我正在使用

 dplyr::mutate

然后写出列的算术和得到总和。但是这些列有 NA ,我想将它们视为零。我能够让它与 rowSums 一起工作(见下文),但现在使用 mutate。使用 mutate 可以使其更具可读性,但也可以让我减去列。示例如下。

require(dplyr)
data(iris)
iris <- tbl_df(iris)
iris[2,3] <- NA
iris <- mutate(iris, sum = Sepal.Length + Petal.Length)

如何确保 Petal.Length 中的 NA 在上述表达式中被处理为零?我知道使用 rowSums 我可以做类似的事情:

iris$sum <- rowSums(DF[,c("Sepal.Length","Petal.Length")], na.rm = T)

但是使用 mutate 更容易设置 even diff = Sepal.Length - Petal.Length。 使用 mutate 完成此操作的建议方法是什么?

注意 post 类似于下面的 Whosebug posts.

Subtract multiple columns ignoring NA

您的 rowSums 的问题是对 DF 的引用(未定义)。这有效:

mutate(iris, sum2 = rowSums(cbind(Sepal.Length, Petal.Length), na.rm = T))

为了区别,你当然可以使用负数:rowSums(cbind(Sepal.Length, -Petal.Length), na.rm = T)

一般的解决方案是使用ifelse或类似的方法将缺失值设置为0(或其他合适的):

mutate(iris, sum2 = Sepal.Length + ifelse(is.na(Petal.Length), 0, Petal.Length))

ifelse 更有效的是 coalescesee examples here. This uses @krlmlr's answer from the previous link (see bottom for the code or use the kimisc package) 的实现。

mutate(iris, sum2 = Sepal.Length + coalesce.na(Petal.Length, 0))

要在整个数据集中替换缺失值,tidyr 包中有 replace_na


@krlmlr 的 coalesce.naas found here

coalesce.na <- function(x, ...) {
  x.len <- length(x)
  ly <- list(...)
  for (y in ly) {
    y.len <- length(y)
    if (y.len == 1) {
      x[is.na(x)] <- y
    } else {
      if (x.len %% y.len != 0)
        warning('object length is not a multiple of first object length')
      pos <- which(is.na(x))
      x[pos] <- y[(pos - 1) %% y.len + 1]
    }
  }
  x
}