These are my Events and the X and Y Coordinates of each event. I am looking to assign the value of "1" to an Event if that Event = 0 < x < 4 & 0 < y < 4 AND the previous Event = x > 4 & y > 4, and assign the value of "0" if the criteria is not met. Here is my initial table:
Event LocX LocY
1 6 6
2 3 2
3 3 7
4 1 4
5 7 4
6 1 2
7 8 5
8 1 1
My final table would look like:
Event LocX LocY Value
1 6 6 0
2 3 2 1
3 3 7 0
4 1 4 0
5 7 4 0
6 1 2 1
7 8 5 0
8 1 1 1
Any help would be appreciated!
A dplyr
way with ifelse
. I named the data frame df1
.
library(dplyr)
df1 %>%
mutate(Value = ifelse(LocX > 0 &
LocX < 4 &
LocY > 0 &
LocY < 4 &
lag(LocX) > 4 &
lag(LocY) > 4, 1, 0))
Event LocX LocY Value
1 1 6 6 0
2 2 3 2 1
3 3 3 7 0
4 4 1 4 0
5 5 7 4 0
6 6 1 2 0
7 7 8 5 0
8 8 1 1 1
Another data.table
approach. It like a translation of neilfws's dplyr approach while using the shift
function to compare values from the previous one.
library(data.table)
setDT(dt)[ ,Value := ifelse(LocX < 4 &
LocY < 4 &
shift(LocX, type = "lag") > 4 &
shift(LocY, type = "lag") > 4,
1, 0)]
dt
Event LocX LocY Value
1: 1 6 6 0
2: 2 3 2 1
3: 3 3 7 0
4: 4 1 4 0
5: 5 7 4 0
6: 6 1 2 0
7: 7 8 5 0
8: 8 1 1 1
Data
dt <- read.table(text = "Event LocX LocY
1 6 6
2 3 2
3 3 7
4 1 4
5 7 4
6 1 2
7 8 5
8 1 1",
header = TRUE)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With