1

我是一个 R 菜鸟,并试图对数据集执行摘要,该数据集汇总了在该 ID 的“B”类型事件之间发生的每个 ID 的事件类型数。这是一个示例来说明:

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”时,我想知道在该 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)

4

2 回答 2

1

这是一个使用data.table. 我们将'data.frame'转换为'data.table'( setDT(df),按'id'分组,我们得到max'type'为'B'的位置的序列,找到行索引( .I),提取该列( $V1) . 然后,我们对数据集进行子集化df[i1]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
于 2016-08-23T19:22:10.447 回答
0

您可以通过 do来cumsum创建新的组变量,然后过滤掉落后于最后一个 B 的类型以及类型 B 本身,因为它们不会被计算在内。然后用和来计算分组的出现次数。B_instancecumsum(type == "B")countidB_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
于 2016-08-23T19:14:15.317 回答