R 为每个组创建增量索引,以其他列为起始行条件

R 为每个组创建增量索引,以其他列为起始行条件,r,dplyr,R,Dplyr,假设我有一个类似的数据集: library(tidyverse) country <- c(rep("Germany", 9), rep("Greece", 9), rep("Turkey", 9), rep("Austria", 9)) date <- rep(seq(ymd('2012-04-07'),ymd('2012-04-15'),by='days'), 4) gyros_eaten <

假设我有一个类似的数据集:

library(tidyverse)

country <- c(rep("Germany", 9), rep("Greece", 9), rep("Turkey", 9), rep("Austria", 9))
date <- rep(seq(ymd('2012-04-07'),ymd('2012-04-15'),by='days'), 4)
gyros_eaten <- c(lag(1:3, n = 2, default = 0), floor(runif(6, min=1, max=4)),
                 lag(1:6, n = 5, default = 0), floor(runif(3, min=1, max=4)),
                 lag(1:2, n = 1, default = 0), floor(runif(7, min=1, max=4)),
                 lag(1:3, n = 2, default = 0), floor(runif(6, min=1, max=4)))
df <- data.frame(country, date, gyros_eaten)
库(tidyverse)

国家我们可以得到第一个
日期
,其中
陀螺>0
,并从
国家的日期中减去所有日期。我们使用
pmax
在自第一次使用本地陀螺以来的
天内保持最大值0

library(dplyr)

df %>%
  arrange(country, date) %>%
  group_by(country) %>%
  mutate(days_since_first_local_gyros = pmax(as.integer(date - 
                            date[which.max(gyros_eaten > 0)]), 0))

#   country date       gyros_eaten days_since_first_local_gyros
#   <chr>   <date>           <dbl>                        <dbl>
# 1 Austria 2012-04-07           0                            0
# 2 Austria 2012-04-08           0                            0
# 3 Austria 2012-04-09           1                            0
# 4 Austria 2012-04-10           1                            1
# 5 Austria 2012-04-11           1                            2
# 6 Austria 2012-04-12           2                            3
# 7 Austria 2012-04-13           2                            4
# 8 Austria 2012-04-14           2                            5
# 9 Austria 2012-04-15           3                            6
#10 Germany 2012-04-07           0                            0
# … with 26 more rows

库(dplyr)
df%>%
安排(国家、日期)%>%
按(国家)划分的组别%>%
变异(从第一次开始的天数)本地陀螺=pmax(整数)(日期-
日期[哪个.max(陀螺仪>0)],0)
#国家日期陀螺仪从第一台本地陀螺仪开始已经吃了几天了
#                                         
#1奥地利2012-04-07 0 0
#2奥地利2012-04-08 0
#3奥地利2012-04-09 10
#4奥地利2012-04-10 1
#5奥地利2012-04-11 1 2
#6奥地利2012-04-12 2 3
#7奥地利2012-04-13 2 4
#8奥地利2012-04-14 2 5
#9奥地利2012-04-15 3 6
#10德国2012-04-07 0
#…还有26行

谢谢,这正是我需要的!