你的问题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
, 请参阅此处的示例。这使用了上一个链接中@krlmlr的答案(请参阅底部的代码或使用基米斯克封装).
mutate(iris, sum2 = Sepal.Length + coalesce.na(Petal.Length, 0))
为了替换数据集范围内的缺失值,有replace_na
in the tidyr
包裹。
@krlmlr 的coalesce.na
, 如这里找到的
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
}