2016-08-23 35 views
1

我是R noob,并且试图对数据集执行摘要,该数据集对该ID的类型“B”的事件之间发生的每个ID总计事件类型的数量。下面是一个示例来说明:基于日期的dplyr中的条件汇总

id <- c('1', '1', '1', '2', '2', '2', '3', '3', '3', '3') 
type <- c('A', 'A', 'B', 'A', 'B', 'C', 'A', 'B', 'C', 'B') 
datestamp <- as.Date(c('2016-06-20','2016-07-16','2016-08-14','2016-07-17' 
         ,'2016-07-18','2016-07-19','2016-07-16','2016-07-19' 
         , '2016-07-21','2016-08-20')) 
df <- data.frame(id, type, datestamp) 

其产生:

> df 
    id type datestamp 
1 1 A 2016-06-20 
2 1 A 2016-07-16 
3 1 B 2016-08-14 
4 2 A 2016-07-17 
5 2 B 2016-07-18 
6 2 C 2016-07-19 
7 3 A 2016-07-16 
8 3 B 2016-07-19 
9 3 C 2016-07-21 
10 3 B 2016-08-20 

事件“B”发生的任何时间,我想知道的是乙事件之前发生的每个事件类型的数量,但在该ID的任何其他B事件之后。 我想直到结束是这样的一个表:

id type B_instance count 
1 1 A   1  2 
2 2 A   1  1 
3 3 A   1  1 
4 3 C   2  1 

在研究,这个问题就来了最靠近:summarizing a field based on the value of another field in dplyr

我一直在努力使这项工作:

df2 <- df %>% 
    group_by(id, type) %>% 
    summarize(count = count(id[which(datestamp < datestamp[type =='B'])])) %>% 
    filter(type != 'B') 

但它错误(即使它工作,它也不会在同一个ID中占用2'B'事件,例如id = 3)

回答

0

您可以使用cumsum通过执行cumsum(type == "B")来创建新的组变量B_instance,然后筛选掉落在最后一个B以及类型B本身之后的类型,因为它们不会被计算在内。然后使用count来计算该组发生的次数为id,B_instancetype

df %>% 
     group_by(id) %>% 
     # create B_instance using cumsum on the type == "B" condition 
     mutate(B_instance = cumsum(type == "B") + 1) %>%  
     # filter out rows with type behind the last B and all B types     
     filter(B_instance < max(B_instance), type != "B") %>% 
     # count the occurrences of type grouped by id and B_instance 
     count(id, type, B_instance) 

# Source: local data frame [4 x 4] 
# Groups: id, type [?] 

#  id type B_instance  n 
# <fctr> <fctr>  <dbl> <int> 
# 1  1  A   1  2 
# 2  2  A   1  1 
# 3  3  A   1  1 
# 4  3  C   2  1 
+0

这个完美的作品!谢谢!出于好奇,为什么cumsum需要也由1? – feyr

+0

递增以匹配实例数,否则将从零开始,而结果会像'0,0,0,1'而不是'1,1,1,2'。 – Psidom

1

下面是使用data.table一个选项。我们将'data.frame'转换为'data.table'(setDT(df),按'id'分组,我们得到'type'为'B'的max位置的序列,找到行索引(.I)然后,我们将数据集(df[i1])进行子集化,删除'type'为'B'的行,按'id','type'和'type'的rleid分组,得到行数作为“计数”。

library(data.table) 
i1 <- setDT(df)[, .I[seq(max(which(type=="B")))] , by = id]$V1 
df[i1][type!="B"][, .(count = .N), .(id, type, B_instance = rleid(type))] 
# id type B_instance count 
#1: 1 A  1  2 
#2: 2 A  1  1 
#3: 3 A  1  1 
#4: 3 C  2  1 
+1

这也很好,谢谢。@ Psidom's dplyr解决方案对我来说更直观。但使用data.table有没有好处,我不知道?或者只是个人喜好? – feyr

+0

@feyr他们都是很好的包。如果你想利用这个赋值(':=')(这里没有完成),哪个data.table可以做到并且效率很高。但是,在这种情况下,psidom的解决方案将与我的一样出色,甚至更加优雅。 – akrun