[R] Method Guidance
Jeff Reichman
re|chm@nj @end|ng |rom @bcg|ob@|@net
Wed Jan 12 14:40:08 CET 2022
Rui
Well that certainly is a lot more straight forward than the direction I was trying and you have introduced me to a couple of new functions. Thank you
Jeff
-----Original Message-----
From: Rui Barradas <ruipbarradas using sapo.pt>
Sent: Wednesday, January 12, 2022 5:08 AM
To: reichmanj using sbcglobal.net; r-help using r-project.org
Subject: Re: [R] Method Guidance
Hello,
Here is a base R solution for what I understand of the question.
It involves ave and cumsum. cumsum of the values of Event_A breaks Event_B in segments and ave applies a function to each segment. To find where are the times B, coerce to logical and have which() take care of it. Data in dput format at the end.
ave(as.logical(df1$Event_B), cumsum(df1$Event_A),
FUN = function(x) {
y <- integer(length(x))
y[x] <- which(x) - 1L
y
})
#[1] 0 1 0 0 1 0 3 0 0 2
More readable, with an auxiliary function.
aux_fun <- function(x) {
y <- integer(length(x))
y[x] <- which(x) - 1L
y
}
ave(as.logical(df1$Event_B), cumsum(df1$Event_A), FUN = aux_fun) #[1] 0 1 0 0 1 0 3 0 0 2
Now assign this result to a df1 column. Here I just test for equality.
new <- ave(as.logical(df1$Event_B), cumsum(df1$Event_A), FUN = aux_fun) identical(new, df1$Time_B) #[1] TRUE
# Data
df1 <-
structure(list(Time = 1:10, Event_A = c(1L, 0L, 0L, 1L, 0L, 0L, 0L, 1L, 0L, 0L), Event_B = c(1L, 1L, 0L, 0L, 1L, 0L, 1L, 1L, 0L, 1L), Time_B = c(0L, 1L, 0L, 0L, 1L, 0L, 3L, 0L, 0L, 2L)), class = "data.frame", row.names = c(NA, -10L))
Hope this helps,
Rui Barradas
Às 00:56 de 12/01/22, Jeff Reichman escreveu:
> R-Help Forum
>
>
>
> Looking for a little guidance. Have an issue were I'm trying to
> determine the time between when Event A happened(In days) to when a
> subsequent Event B happens. For Example at Time 1 Evat A happens and
> subsequently Event B happens at the same day (0) and the next day (1)
> then Event A happens again at time 4 and Event B happens the next day
> and 3 days later so on and so forth. I gather there is no function
> that will do that so I suspect I will need to grate so sour of do while loop? Any suggestions?
>
>
>
>
>
> Time Event_A Event_B Time_B
>
> 1 1 1
> 0
>
> 2 0 1
> 1
>
> 3 0 0
> 0
>
> 4 1 0
> 0
>
> 5 0 1
> 1
>
> 6 0 0
> 0
>
> 7 0 1
> 3
>
> 8 1 1
> 0
>
> 9 0 0
> 0
>
> 10 0 1 2
>
>
>
>
> Jeff Reichman
>
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list