Ignoring NA when summing multiple columns with dplyr

久未见 提交于 2021-02-04 19:29:05

问题


I am summing across multiple columns, some that have NA. I am using

 dplyr::mutate

and then writing out the arithmetic sum of the columns to get the sum. But the columns have NA and I would like to treat them as zero. I was able to get it to work with rowSums (see below), but now using mutate. Using mutate allows to make it more readable, but can also allow me to subtract columns. The example is below.

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

How do I ensure that NA in Petal.Length is handled as zero in the above expression? I know using rowSums I can do something like:

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

but with mutate it is easier to set even diff = Sepal.Length - Petal.Length. What would be a suggested way to accomplish this using mutate?

Note the post is similar to below stackoverflow posts.

Sum across multiple columns with dplyr

Subtract multiple columns ignoring NA


回答1:


The problem with your rowSums is the reference to DF (which is undefined). This works:

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

For difference, you could of course use a negative: rowSums(cbind(Sepal.Length, -Petal.Length), na.rm = T)

The general solution is to use ifelse or similar to set the missing values to 0 (or whatever else is appropriate):

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

More efficient than ifelse would be an implementation of coalesce, see 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))

To replace missing values data-set wide, there is replace_na in the tidyr package.


@krlmlr's coalesce.na, as 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
}


来源:https://stackoverflow.com/questions/36557358/ignoring-na-when-summing-multiple-columns-with-dplyr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!