我有三种不同类型的事件(Pass
、RHM
和REM
),见下面的例子;
Event | Start |
---|---|
RHM | 668.043 |
Pass | 668.873 |
Pass | 675.213 |
RHM | 675.383 |
REM | 678.900 |
Pass | 680.163 |
Pass | 683.543 |
现在我想知道根据事件类型的不同,一个特定的传球到另一个偶数的开始时间之间的差异.更具体地说,对于每Pass
个人,我想知道现在的Pass
人和以前的Pass
人,以前的RHM
人和以前的REM
人之间的区别是什么.
因此,对于第一遍,也就是数据帧中的第二行(Start=668.873),与前Pass
的差异是NaN(因为之前没有),与前RHM
的差异是668.873-668.043=0.83,而与前REM
的差异再次是NaN,因为没有.理想情况下,这将导致以下结果;
Event | Time since last Pass
|
Time since last RHM
|
Time since last REM
|
---|---|---|---|
Pass | NaN | 0.830 | NaN |
Pass | 6.340 | 7.170 | NaN |
Pass | 4.950 | 4.780 | 1.263 |
Pass | 3.380 | 8.160 | 4.643 |
使其更加复杂的是,DataFrame有两个额外的变量,用于循环上面的变量:Category
和Situation
;
Category | Situation | Event | Start |
---|---|---|---|
R1 | 1 | RHM | 668.043 |
R1 | 1 | Pass | 668.873 |
R1 | 1 | Pass | 675.213 |
R1 | 1 | RHM | 675.383 |
R1 | 1 | REM | 678.900 |
R1 | 1 | Pass | 680.163 |
R1 | 1 | Pass | 683.543 |
R2 | 2 | RHM | 668.043 |
R2 | 2 | Pass | 668.873 |
R2 | 2 | Pass | 675.213 |
R2 | 2 | RHM | 675.383 |
R2 | 3 | REM | 678.900 |
R2 | 3 | Pass | 680.163 |
R2 | 3 | Pass | 683.543 |
我已经使用了当前的代码,它适用于1种情况,但它需要重新开始为每种情况.我不知道该怎么做.我在考虑使用dplyr
,但不知道如何将其与for循环相结合.
for (i in 1:nrow(x)) {
# PASSES
# look in rows above the current row and search for last row containing "Pass"
previousPasses <- which(x$Event[1:i - 1] == "Pass")
# get last of these passes
lastPass <- previousPasses[length(previousPasses)]
# if there are no previous passes, then leave the TimeLastPass column blank
if (length(lastPass) == 0) {
x$TimeLastPass[i] <- NaN
} else {
# otherwise, fill in the TimeLastPass column with the time of the last pass
x$TimeLastPass[i] <- round(x$Start[lastPass] - x$Start[i],2)
}
### REM
# look in rows above the current row and search for last row containing "REM"
previousREMs <- which(x$Event[1:i - 1] == "Referential Eye Movement")
# get last of these REMs
lastREM <- previousREMs[length(previousREMs)]
# if there are no previous REMs, then leave the TimeLastREM column blank
if (length(lastREM) == 0) {
x$TimeLastREM[i] <- NaN
} else {
# otherwise, fill in the TimeLastREM column with the time of the last REM
x$TimeLastREM[i] <- round(x$Start[lastREM] - x$Start[i], 2)
}
### RHM
# look in rows above the current row and search for last row containing "RHM"
previousRHMs <- which(x$Event[1:i - 1] == "Referential Head Movement")
# get last of these RHMs
lastRHM <- previousRHMs[length(previousRHMs)]
# if there are no previous RHMs, then leave the TimeLastRHM column blank
if (length(lastRHM) == 0) {
x$TimeLastRHM[i] <- NaN
} else {
# otherwise, fill in the TimeLastRHM column with the time of the last RHM
x$TimeLastRHM[i] <- round(x$Start[lastRHM] - x$Start[i],2)
}
}