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.