r - 使用 dplyr 汇总时省略 NA

标签 r dplyr

我的问题涉及使用 summarise_each 总结具有多列(50 列)的数据框dplyr 中的函数。
列中的数据条目是二进制的(0=负,1=正),我的目标是获得 colsums 和百分比正数。
问题是某些列有 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(total.count) 为:
length(df$x1[!is.na(df$x1)])

[1] 8

相反,我得到了以下内容,其中包括 NA:
length(df$x1)

[1] 10

我还希望 x1 的百分比(positive.pctg)为:
sum(df$x1,na.rm=T)/length(df$x1[!is.na(df$x1)])

[1] 0.5

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

[1] 0.4

如何在 dplyr 中计算省略 NAs 的次数?似乎功能n()length()不要采取任何
类似 na.omit/na.rm/complete.cases 的参数.
任何帮助将不胜感激。

最佳答案

尝试

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)

关于r - 使用 dplyr 汇总时省略 NA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28692578/

相关文章:

r - 传单呈现不正确的国家

r - 将两个嵌套 tibble 变量相乘

r - na.locf 使用 dplyr 中的 group_by

R 对行子集的组执行计算

r - 为什么更改 x 轴在绘图中不起作用?

r - bookdown 将章节转换为章节

r - car::Anova拥有不与主题内因素相互作用的协变量的方式

r - 在 R 中绘制二进制目标 (mlr) 的部分依赖图

r - 在 R 中标记唯一值

r - 使用 dplyr mutate 根据列名向量创建新列