使用dplyr summarise计数时忽略NA值

4

我的问题涉及使用dplyr中的summarise_each函数对具有多个列(50列)的数据框进行汇总。 列中的数据条目是二进制的(0=负面, 1=积极),我想要得到列总和和积极百分比。 问题在于某些列具有NA值,我希望在计算总数和百分比时将其排除。 以下是一个最小示例:

library(dplyr)
library(tidyr)
df=data.frame(
  x1=c(1,0,0,NA,0,1,1,NA,0,1),
  x2=c(1,1,NA,1,1,0,NA,NA,0,1),
  x3=c(0,1,0,1,1,0,NA,NA,0,1),
  x4=c(1,0,NA,1,0,0,NA,0,0,1),
  x5=c(1,1,NA,1,1,1,NA,1,0,1))

> df
   x1 x2 x3 x4 x5
1   1  1  0  1  1
2   0  1  1  0  1
3   0 NA  0 NA NA
4  NA  1  1  1  1
5   0  1  1  0  1
6   1  0  0  0  1
7   1 NA NA NA NA
8  NA NA NA  0  1
9   0  0  0  0  0
10  1  1  1  1  1

df %>%
  summarise_each(funs(total.count=n(), positive.count=sum(.,na.rm=T),positive.pctg=sum(.,na.rm=T)*100/n())) %>%
  gather(key,fxn,x1_total.count:x5_positive.pctg) %>%
  separate(key,c("col","funcn"),sep="\\_") %>%
  spread(funcn,fxn)

  col positive.count positive.pctg total.count
1  x1              4            40          10
2  x2              5            50          10
3  x3              4            40          10
4  x4              3            30          10
5  x5              7            70          10

我希望在上面的表格中得到的是例如x1的总数(total.count):
length(df$x1[!is.na(df$x1)])

[1] 8

相反,我得到了以下等价物,其中包括NAs:
length(df$x1)

[1] 10

我还希望为x1计算出正值百分比(positive.pctg):

sum(df$x1,na.rm=T)/length(df$x1[!is.na(df$x1)])

[1] 0.5

相反,我得到了以下等价内容,其中包括NAs:
sum(df$x1,na.rm=T)/length(df$x1)

[1] 0.4

我该如何在dplyr中进行计数但忽略NA值?似乎函数n()length()不像na.omit/na.rm/complete.cases那样接受任何参数。 非常感谢您的帮助。
1个回答

3

尝试

df %>%
    summarise_each(funs(total.count=sum(!is.na(.)), positive.count=sum(.,na.rm=T),positive.pctg=sum(.,na.rm=T)*100/sum(!is.na(.))))%>%
    gather(key,fxn,x1_total.count:x5_positive.pctg) %>%
    separate(key,c("col","funcn"),sep="\\_") %>%
    spread(funcn,fxn)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接