使用 dplyr summarize 计算时省略 NA
omit NAs when tallying using dplyr summarise
我的问题涉及使用 dplyr 中的 summarise_each
函数汇总具有多列(50 列)的数据框。
列中的数据条目是二进制的(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
我希望在上面的 table 中得到的是,例如 x1 的总计(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 省略 NA 中进行计数?似乎函数 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)
我的问题涉及使用 dplyr 中的 summarise_each
函数汇总具有多列(50 列)的数据框。
列中的数据条目是二进制的(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
我希望在上面的 table 中得到的是,例如 x1 的总计(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 省略 NA 中进行计数?似乎函数 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)