基于ifelse语句/另一列,将时间增量添加到POSIXct

时间:2018-05-29 06:51:41

标签: r if-statement

我的数据集包括在团队运动比赛期间发生的带时间戳的事件。每轮5分钟。我希望添加每个时间戳发生的累积时间,但是我只有在指定时间内发生事件的时间。

我的数据集的一个例子是:

 > head(OutcomeData$Match_EndingRound, 15)
 [1] 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2
> head(OutcomeData$TimeStamp, 15)
 [1] "1899-12-31 00:02:36 UTC" "1899-12-31 00:02:36 UTC" "1899-12-31 00:03:01 UTC" "1899-12-31 00:03:01 UTC" "1899-12-31 00:03:21 UTC"
 [6] "1899-12-31 00:03:21 UTC" "1899-12-31 00:04:37 UTC" "1899-12-31 00:04:37 UTC" "1899-12-31 00:02:19 UTC" "1899-12-31 00:02:19 UTC"
[11] "1899-12-31 00:02:19 UTC" "1899-12-31 00:02:19 UTC" "1899-12-31 00:02:09 UTC" "1899-12-31 00:02:09 UTC" "1899-12-31 00:02:09 UTC"

dput(head(OutcomeData$TimeStamp, 15))
structure(c(-2209075044, -2209075044, -2209075019, -2209075019, 
-2209074999, -2209074999, -2209074923, -2209074923, -2209075061, 
-2209075061, -2209075061, -2209075061, -2209075071, -2209075071, 
-2209075071), class = c("POSIXct", "POSIXt"), tzone = "UTC")

我希望为时间戳数据添加5分钟,每轮= 2.当轮数等于3,4和5(我的示例中未显示)时,我希望添加10,15和20分钟分别。

我尝试过以下方法:

OutcomeData$CumulativeTime <- ifelse(OutcomeData$Match_EndingRound==1, OutcomeData$TimeStamp,
                              ifelse(OutcomeData$Match_EndingRound==2, OutcomeData$TimeStamp + 300,
                              ifelse(OutcomeData$Match_EndingRound==3, OutcomeData$TimeStamp,
                              ifelse(OutcomeData$Match_EndingRound==4, OutcomeData$TimeStamp,
                              ifelse(OutcomeData$Match_EndingRound==5, OutcomeData$TimeStamp + 1200, OutcomeData$TimeStamp)))))

虽然我最终得到了这个输出并且不确定我哪里出错了?

 head(OutcomeData$CumulativeTime, 15)
 [1] -2209075044 -2209075044 -2209075019 -2209075019 -2209074999 -2209074999 -2209074923 -2209074923 -2209074761 -2209074761 -2209074761 -2209074761
[13] -2209074771 -2209074771 -2209074771

我的预期输出是:

> head(OutcomeData$TimeStamp, 15)
     [1] "1899-12-31 00:02:36 UTC" "1899-12-31 00:02:36 UTC" "1899-12-31 00:03:01 UTC" "1899-12-31 00:03:01 UTC" "1899-12-31 00:03:21 UTC"
     [6] "1899-12-31 00:03:21 UTC" "1899-12-31 00:04:37 UTC" "1899-12-31 00:09:37 UTC" "1899-12-31 00:07:19 UTC" "1899-12-31 00:07:19 UTC"
    [11] "1899-12-31 00:07:19 UTC" "1899-12-31 00:07:19 UTC" "1899-12-31 00:07:09 UTC" "1899-12-31 00:07:09 UTC" "1899-12-31 00:07:09 UTC"

非常感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

通常,您似乎希望为每个时间戳添加5*(OutcomeData$Match_EndingRound-1)分钟。所以试试吧:

OutcomeData$TimeStamp+60*5*(OutcomeData$Match_EndingRound-1)