简体   繁体   English

当所有元素均为NA时作为操作结果的NA

[英]NA as result of operation when all elements are NA

This might be slightly silly but I would appreciate a better way to deal with this problem. 这可能有点愚蠢,但我希望能找到一种更好的方法来解决此问题。 I have a dataframe as the following 我有一个数据框如下

a <- matrix(1,5,3)
a[1:2,2] <- NA
a[1,c(1,3)] <- NA
a[3:5,2] <- 2
a[2:5,3] <- 3 
a <- data.frame(a)
colnames(a) = c("First", "Second", "Third")

I want to sum only some of, say, the columns but I would like to keep the NAs when all elements in the summed columns are NA. 我只想对某些列求和,但是当求和列中的所有元素均为NA时,我想保留NA。 In short, if I sum First and Second columns I want to get something like 简而言之,如果我将第一列和第二列加起来,我想得到类似

mySum <- c(NA, 1, 3, 3, 3)

Neither of the two options below provides what I want 下面的两个选项都不提供我想要的

rowSums(a[, c("First", "Second")])
rowSums(a[, c("First", "Second")], na.rm=TRUE)

but on the positive side I have resolved this by using a combination of is.na and all 但从积极的方面来说,我已经结合使用is.na和所有

mySum <- rowSums(a[, c("First", "Second")], na.rm=TRUE)
iNA = apply(a[, c("First", "Second")], 2, is.na)
iAllNA = apply(iNA, 1, all)
mySum[iAllNA] = NA

This feels slightly awkward though so I was wondering if there is a smarter way to handle this. 但是,这感觉有点尴尬,因此我想知道是否有更聪明的方法来处理此问题。

Using apply with margin = 1 for every row if all the row elements are NA we return NA or else we return the sum of them. 如果所有行元素均为NA则对每一行使用apply margin = 1 ,则返回NA ,否则返回它们的sum

apply(a[c("First", "Second")], 1, function(x) 
                          ifelse(all(is.na(x)), NA, sum(x, na.rm = TRUE)))

#[1] NA  1  3  3  3
mycols = c("First", "Second")
replace(x = rowSums(a[mycols], na.rm = TRUE),
        list = rowSums(is.na(a[mycols])) == length(mycols),
        values = NA)
#[1] NA  1  3  3  3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM