[R] Method Guidance
Bill Dunlap
w||||@mwdun|@p @end|ng |rom gm@||@com
Fri Jan 14 02:50:35 CET 2022
Suppose your data were represented as parallel vectors "time" and "type",
meaning that at time[i] a type[i] event occurred. You didn't say what you
wanted if there were a run of "A" or "B". If you are looking for the time
span between the last of a run of one sort of event and the first of a run
of the other sort of event then the following can be used.
f <- function(time, type, fromType, toType) {
# return times of (fromTime) last of a run of 'fromType' and
# (toTime) first of subsequent run of 'toType for each such transition.
stopifnot(length(time)==length(type),
!anyNA(type),
!anyNA(time),
!is.unsorted(time),
length(fromType)==1,
length(toType)==1)
i <- seq_len(length(time)-1)
iBeforeChange <- which((type[i] == fromType) & (type[i+1] == toType))
data.frame(fromTime=time[iBeforeChange], toTime=time[iBeforeChange+1L])
}
E.g.,
> d <- data.frame(time=c(101,102,102,105,107,111,115),
type=c("A","A","B","A","B","B","A"))
> d
time type
1 101 A
2 102 A
3 102 B
4 105 A
5 107 B
6 111 B
7 115 A
> f(time=d$time, type=d$type, fromType="A", toType="B")
fromTime toTime
1 102 102
2 105 107
> with(.Last.value, toTime - fromTime)
[1] 0 2
> f(time=d$time, type=d$type, fromType="B", toType="A")
fromTime toTime
1 102 105
2 111 115
> with(.Last.value, toTime - fromTime)
[1] 3 4
With the dplyr package you can avoid the index 'i' by using lag() inside of
mutate(). E.g.,
> d |> mutate(AtoB = (lag(type)=="A" & type=="B"))
time type AtoB
1 101 A FALSE
2 102 A FALSE
3 102 B TRUE
4 105 A FALSE
5 107 B TRUE
6 111 B FALSE
7 115 A FALSE
-Bill
On Tue, Jan 11, 2022 at 4:56 PM Jeff Reichman <reichmanj using sbcglobal.net>
wrote:
> 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.
>
[[alternative HTML version deleted]]
More information about the R-help
mailing list