2016-03-15 77 views
0

我试图简化这与几个语句。不知道如何去做(或者如果我可以),但任何能够让我接近或尽可能少的步骤的人。我正在使用dplyr和lubridate。我有一个名为OutofRange(sample)的数据库;dplyr group_by逻辑值

OutOfRange %>% select(OutRange, TouchVPOC) 
Source: local data frame [341 x 2] 

    OutRange TouchVPOC 

    (lgl)  (lgl) 

1  FALSE  TRUE 
2  FALSE  FALSE 
3  FALSE  TRUE 
4  FALSE  FALSE 
5  FALSE  TRUE 

OutOfRange %>% select(OutRange, TouchVPOC) %>% filter(OutRange == T) %>% tally 
Source: local data frame [1 x 1] 

     n (int) 
1 37 

OutOfRange %>% select(OutRange, TouchVPOC) %>% filter(OutRange == T, TouchVPOC == T) %>% tally 
Source: local data frame [1 x 1] 

     n (int) 
1 15 

15/37 
[1] 0.4054054 

因此,如果可能的话,我正在寻找类似这样的最终结果,其中CountofDataFrame是所有行的计数; OutRange & TouchVPOC是TRUE值的计数;和Pct = TouchVPOC/OutRange。

CountOfDataFrame OutRange TouchVPOC Pct 
      341  37   15 .40 

我明白了,我可能会问很多..我是新来的,欢迎任何建议。只是寻找一个基础或开始在正确的方向。

+2

请阅读关于[如何提出一个好问题](http://stackoverflow.com/help/how-to-ask)以及如何给出[可重现的例子](http:// stackoverflow.com/questions/5963269)。这会让其他人更容易帮助你。 – zx8754

+0

一些相关的*聚合*帖子:[R分组功能:sapply vs. lapply vs. apply。与tapply与通过与聚合](http://stackoverflow.com/questions/3505701),[同时聚合多个变量](http://stackoverflow.com/questions/9723208),[如何总结一个变量按照群组?](http://stackoverflow.com/q/1660124) – zx8754

+0

为了给你一个想法,试试'sum(c(TRUE,FALSE,TRUE))'。 – zx8754

回答

0

我建议你先把数据先整理成整齐的格式,然后用group_by/summarize/mutate做下面的聚合和百分比计算。

a <- data.frame(OutRange = c(TRUE, FALSE, FALSE, FALSE, FALSE), 
      TouchVPOC = c(TRUE, TRUE, TRUE, FALSE, FALSE)) 

> a 
    OutRange TouchVPOC 
1  TRUE  TRUE 
2 FALSE  TRUE 
3 FALSE  TRUE 
4 FALSE  FALSE 
5 FALSE  FALSE 

library(tidyr) 
a %>% 
    gather(type, value, OutRange:TouchVPOC) %>% 
    group_by(type) %>% 
    summarize(true_count = sum(value)) %>% 
    mutate(total = sum(true_count), Pct = true_count/total) 

Source: local data frame [2 x 4] 

     type true_count total Pct 
     (chr)  (int) (int) (dbl) 
1 OutRange   1  4 0.25 
2 TouchVPOC   3  4 0.75 
+0

谢谢!没有意识到tidyr以这种方式工作。为我打开新的大门。运行这个之后,我意识到我需要在过滤数据的前一步。但是在变更原始数据的时候,我能够在表格中添加列。换句话说,我不是过滤,而是突变了一个名为OutRange_Touch的新列;其中有窍门! – marts01