I have a data frame with some NA values. I need the sum of two of the columns. If a value is NA, I need to treat it as zero.
我有一个带有一些NA值的数据框。我需要两列的总和。如果值为NA,我需要将其视为零。
a b c d
1 2 3 4
5 NA 7 8
Column e should be the sum of b and c:
列e应该是b和c的总和:
e
5
7
I have tried a lot of things, and done two dozen searches with no luck. It seems like a simple problem. Any help would be appreciated!
我尝试过很多东西,并且没有运气就进行了二十多次搜索。这似乎是一个简单的问题。任何帮助,将不胜感激!
2 个解决方案
#1
16
dat$e <- rowSums(dat[,c("b", "c")], na.rm=TRUE)
dat
# a b c d e
# 1 1 2 3 4 5
# 2 5 NA 7 8 7
#2
1
Here is another solution, with concatenated ifelse()
:
这是另一个解决方案,带有连接的ifelse():
dat$e <- ifelse(is.na(dat$b) & is.na(dat$c), dat$e <-0, ifelse(is.na(dat$b), dat$e <- 0 + dat$c, dat$b + dat$c))
# a b c d e
#1 1 2 3 4 5
#2 5 NA 7 8 7
Edit, here is another solution that uses with
as suggested by @kasterma in the comments, this is much more readable and straightforward:
编辑,这是另一个使用@kasterma在评论中建议使用的解决方案,它更具可读性和直接性:
dat$e <- with(dat, ifelse(is.na(b) & is.na(c ), 0, ifelse(is.na(b), 0 + c, b + c)))
#1
16
dat$e <- rowSums(dat[,c("b", "c")], na.rm=TRUE)
dat
# a b c d e
# 1 1 2 3 4 5
# 2 5 NA 7 8 7
#2
1
Here is another solution, with concatenated ifelse()
:
这是另一个解决方案,带有连接的ifelse():
dat$e <- ifelse(is.na(dat$b) & is.na(dat$c), dat$e <-0, ifelse(is.na(dat$b), dat$e <- 0 + dat$c, dat$b + dat$c))
# a b c d e
#1 1 2 3 4 5
#2 5 NA 7 8 7
Edit, here is another solution that uses with
as suggested by @kasterma in the comments, this is much more readable and straightforward:
编辑,这是另一个使用@kasterma在评论中建议使用的解决方案,它更具可读性和直接性:
dat$e <- with(dat, ifelse(is.na(b) & is.na(c ), 0, ifelse(is.na(b), 0 + c, b + c)))