2016-04-11 25 views
1

我正在跨多列進行求和,其中一些列有NA。我正在使用使用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) 

但發生變異更容易設置,甚至DIFF = Sepal.Length - Petal.Length。 什麼是建議的方式來完成這個使用mutate?

注後類似於

http://stackoverflow.com/questions/28873057/sum-across-multiple-columns-with-dplyr 
http://stackoverflow.com/questions/23255318/subtract-multiple-columns-ignoring-na 

回答

2

的問題與您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更有效的將是​​3210的實現,see examples here。這使用@ krlmlr從上一個鏈接的答案(請參閱底部的代碼或使用kimisc package)。

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

要替換缺失值數據集寬,存在在tidyrreplace_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 
}