about the equivalent command for forvalues

[亡魂溺海] 提交于 2019-12-04 07:06:24

问题


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), rep(2, 3), rep(3, 3)), 
               event=c(1, 1, 0, 0, 1, 1, 0, 1, 1, 0), 
               eventcount=c(1, 2, 0, 0, 1, 2, 0, 1, 2, 0), 
               firstevent=c(1, 0, 0, 0, 1, 0, 0, 1, 0, 0), 
               time=c(100, 250, 150, 300, 240, 400, 150, 350, 700, 200) )

When I would like to pick up the event within a specific duration of time from the first event. In this case, I would like to detect the second event within 100days-150days. In Stata, we can use

gen event2=1 if id==id[_n-1]& time-time[_n-1]>100 & time-time[_n-1]<=150 & firstevent[_n-1]==1 & firstevent==0 & event==1
forvalues i = 2/3
{
replace event2=1 if id==id[_n-`i']& time-time[_n-`i']>100 &time-time[_n-`i']<=150 & firstevent[_n-`i']==1 & firstevent==0 & event==1
}

In this case,

data_after <- data.frame(id=c(rep(1, 4), rep(2, 3), rep(3, 3)), 
                     event=c(1, 1, 0, 0, 1, 1, 0, 1, 1, 0),  
                     eventcount=c(1, 2, 0, 0, 1, 2, 0, 1, 2, 0),  
                     firstevent=c(1, 0, 0, 0, 1, 0, 0, 1, 0, 0), 
                     time=c(100, 250, 150, 300, 240, 400, 150, 350, 700, 200),  
                     event2=c(NA, 1, NA, NA, NA, NA, NA, NA, NA, NA))

How should I write this in R ?


回答1:


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


来源:https://stackoverflow.com/questions/54791188/about-the-equivalent-command-for-forvalues

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!