我正在对多列求和,有些列有 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 甚至可以更容易地设置 diff = Sepal.Length - Petal.Length。
使用 mutate 完成此操作的建议方法是什么?
请注意,该帖子类似于以下 stackoverflow 帖子。
Sum across multiple columns with dplyr
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
更高效将是 coalesce
的实现, see examples here .这使用了来自上一个链接的@krlmlr 的回答(代码见底部或使用 kimisc package)。mutate(iris, sum2 = Sepal.Length + coalesce.na(Petal.Length, 0))
要替换数据集范围内的缺失值,有
replace_na
在 tidyr
包裹。@krlmlr 的
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
}
关于r - 使用 dplyr 对多列求和时忽略 NA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36557358/