[R] If Loop With Lagged Variable
Phillip Heinrich
herd_dog @end|ng |rom cox@net
Thu Sep 19 18:27:13 CEST 2019
Attached is every at bat for the Arizona Diamondback’s first three games of 2018 – BBdata1.rda. I added the Date and DHCode variables by parsing the first variable labeled GameID.
BBdata2 is a reduced dataset with five variables as shown in the str() command.
data.frame': 234 obs. of 5 variables:
$ GameID : Factor w/ 3 levels "ARI201803290",..: 1 1 1 1 1 1 1 1 1 1 ...
$ Date : Date, format: "2018-03-29" "2018-03-29" "2018-03-29" "2018-03-29" ...
$ DHCode : Factor w/ 1 level "0": 1 1 1 1 1 1 1 1 1 1 ...
$ GameNum: num 1 1 1 1 1 1 1 1 1 1 ...
$ Date2 : Date, format: NA "2018-03-29" "2018-03-29" "2018-03-29" ...
I’m trying to increment the GameNum (game number) to game 2 when the date changes from 2018-03-29 to 2018-03-30 in row 81 and to game 3 in row 165.
According to my R for Dummies book the following code should work but it doesn’t. I keep getting the following error. Any suggestions?
if(ari18.test3$Date > lag(ari18.test3$Date)) {ari18.test3$gameNum <- ari18.tesm3$GameNum + 1}
Warning message:
In if (ari18.test3$Date > lag(ari18.test3$Date)) { :
the condition has length > 1 and only the first element will be used
>
Thanks.
More information about the R-help
mailing list