在dplyr行总和中忽略NA [英] ignore NA in dplyr row sum

查看:208
本文介绍了在dplyr行总和中忽略NA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 数据< p>是否有一个优雅的方法来处理NA为0(na.rm = TRUE)在dplyr? -  data.frame(a = c(1,2,3,4),b = c(4,NA,5,6),c = c(7,8,9,NA))

data%>%mutate(sum = a + b + c)

abc sum
1 4 7 12
2 NA 8 NA
3 5 9 17
4 6 NA NA

但我喜欢得到

abc sum
1 4 7 12
2 NA 8 10
3 5 9 17
4 6 NA 10

即使我知道这不是

解决方案

您可以使用以下内容:

  library(dplyr)
data%>%
#rowwise将确保在每行上执行sum操作
rowwise()%> %
#then一个简单的sum(...,na.rm = TRUE)足以导致你需要的
mutate(sum = sum(a,b,c,na.rm = TRUE ))

输出:

 资料来源:本地资料框[4 x 4] 
群组:< by行>

abc sum
(dbl)(dbl)(dbl)(dbl)
1 1 4 7 12
2 2 NA 8 10
3 3 5 9 17
4 4 6 NA 10


is there an elegant way to handle NA as 0 (na.rm = TRUE) in dplyr?

data <- data.frame(a=c(1,2,3,4), b=c(4,NA,5,6), c=c(7,8,9,NA))

data %>% mutate(sum = a + b + c)

a  b  c sum
1  4  7  12
2 NA  8  NA
3  5  9  17
4  6 NA  NA

but I like to get

a  b  c sum
1  4  7  12
2 NA  8  10
3  5  9  17
4  6 NA  10

even if I know that this is not the desired result in many other cases

解决方案

You could use this:

library(dplyr)
data %>% 
  #rowwise will make sure the sum operation will occur on each row
  rowwise() %>% 
  #then a simple sum(..., na.rm=TRUE) is enough to result in what you need
  mutate(sum = sum(a,b,c, na.rm=TRUE))

Output:

Source: local data frame [4 x 4]
Groups: <by row>

      a     b     c   sum
  (dbl) (dbl) (dbl) (dbl)
1     1     4     7    12
2     2    NA     8    10
3     3     5     9    17
4     4     6    NA    10

这篇关于在dplyr行总和中忽略NA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆