about the equivalent command for forvalues

前端 未结 1 1303
情书的邮戳
情书的邮戳 2021-01-29 12:05

If we have multiple event outcomes as a long format like this (actual data contain many ids, this is a simplified data).

data <- data.frame(id=c(rep(1, 4), re         


        
相关标签:
1条回答
  • 2021-01-29 12:40
    intervals = ave(
        data$time,
        data$id,
        FUN = function(x)
            c(0, diff(x))
    )
    intervals
    # [1]    0  150 -100  150    0  160 -250    0  350 -500
    
    meets_duration_requirement = ave(
        intervals,
        data$id,
        FUN = function(x)
            x >= 100 & x <= 150
    ) == 1 & data$event == 1
    
    choose_second = meets_duration_requirement == 1 &
        ave(meets_duration_requirement, data$id, FUN = seq_along) == 2 #if you want third event, change this to 3
    
    replace(x = rep(NA, NROW(data)),
            list = choose_second,
            1)
    # [1] NA  1 NA NA NA NA NA NA NA NA
    
    0 讨论(0)
提交回复
热议问题