R根据值的计数创建一个新向量,直到一个值的第一个实例一个现有向量

R creating a new vector based on a count of values up to the first instance of a value an existing vector

我如何创建一个新变量 "CountWK",该变量基于 "WK" 中出现的值的计数,直到 "Performance" 分组中的第一个“1”实例出现通过 "ID"?

ID<-c('A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'C', 'C')
WK<-c(1, 2, 3, 1, 2, 3, 1, 2, 3, 4, 5)
Performance<-c(0,1,1,0,1,0,0,1,0,1,1)
Data<-data.frame(ID, WK, Performance)

因此,对于 ID "A" CountWk 将为“2”,对于 "B" 为“2”,对于 C 为“2”且值为 N/A in "CountWk" 除了在 "Performance".

中包含“1”的第一个实例的行之外的每一行

下面是我将如何使用 data.table

来解决这个问题

首先使用.Imatch

找到行索引
library(data.table)
indx <- setDT(Data)[, .I[match(1L, Performance)], by = ID]$V1

然后通过该索引

WK分配给CountWk
Data[indx, CountWk := WK][]
#     ID WK Performance CountWk
#  1:  A  1           0      NA
#  2:  A  2           1       2
#  3:  A  3           1      NA
#  4:  B  1           0      NA
#  5:  B  2           1       2
#  6:  B  3           0      NA
#  7:  C  1           0      NA
#  8:  C  2           1       2
#  9:  C  3           0      NA
# 10:  C  4           1      NA
# 11:  C  5           1      NA

一个选项使用dplyr

library(dplyr)
Data %>% 
     group_by(ID) %>% 
     mutate(CountWk= ifelse(cumsum(Performance==1)==1 & Performance!=0,
                 WK, NA_real_))
#    ID WK Performance CountWk
#1   A  1           0      NA
#2   A  2           1       2
#3   A  3           1      NA
#4   B  1           0      NA
#5   B  2           1       2
#6   B  3           0      NA
#7   C  1           0      NA
#8   C  2           1       2
#9   C  3           0      NA
#10  C  4           1      NA
#11  C  5           1      NA

或没有 ifelse

  Data %>%
      group_by(ID) %>%
      mutate(CountWk= (NA^!(cumsum(Performance==1)==1 & Performance!=0)) *WK)

或使用base R

 Data$CountWk <- with(Data, (NA^!(ave(Performance==1, ID, FUN=cumsum)==1&
                        Performance!=0)) * WK)