I have a data.frame with difftimes created with hms::hms
on it. I know I can use arrange()
and diff()
to check the time elapsed between each observation.
我有一个带有hms :: hms创建的difftimes的data.frame。我知道我可以使用arrange()和diff()来检查每次观察之间经过的时间。
How can I create a $session
variable that changes its value when the time elapsed is bigger than a predefined value?
如何在经过的时间大于预定义值时创建一个更改其值的$ session变量?
For example, given the data below:
例如,给出以下数据:
hour time_elapsed
15:58:05 NA
15:58:11 6
15:58:17 6
15:58:44 27
15:58:51 7
15:58:57 6
Considering values bigger than 25 as the breaking point, we would have:
考虑大于25的值作为突破点,我们将:
hour time_elapsed session
15:58:05 NA 1
15:58:11 6 1
15:58:17 6 1
15:58:44 27 2
15:58:51 7 2
15:58:57 6 2
Thanks in advance!
提前致谢!
1 个解决方案
#1
0
We can replace
the NA
with 0, then create a logical condition and do the cumulative sum
我们可以用0替换NA,然后创建逻辑条件并进行累积求和
df1$session <- with(df1, cumsum(replace(time_elapsed, is.na(time_elapsed), 0) >25) + 1)
#1
0
We can replace
the NA
with 0, then create a logical condition and do the cumulative sum
我们可以用0替换NA,然后创建逻辑条件并进行累积求和
df1$session <- with(df1, cumsum(replace(time_elapsed, is.na(time_elapsed), 0) >25) + 1)