我的问题涉及使用 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/