2015-02-24 56 views
4

我的问题涉及使用dplyr中的summarise_each函数汇总具有多列(50列)的数据帧。 列中的数据条目是二进制(0 =负数,1 =正数),我的目标是获得colsums和百分比正数。 问题是有些列有NAs,我希望在总计和百分比的计算中排除这些。 下面是一个小例子:在使用dplyr汇总计算时省略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 

我希望在上面的表中得到的是例如,总(total.count)为X1为:

length(df$x1[!is.na(df$x1)]) 

[1] 8 

相反,我得到一个

length(df$x1) 

[1] 10 

和我也希望对于x1为百分比(positive.pctg):

下文中,其中包括NAS的等效
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 ommiting来港?看起来功能n()length()不采取任何 参数,如na.omit/na.rm/complete.cases。 任何援助将不胜感激。

回答

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) 
+0

好的,谢谢 – amo 2015-02-24 12:59:18