Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign value to row if row and previous row meet requirement

Tags:

dataframe

r

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!

like image 499
SoccerAnalytics26 Avatar asked Mar 08 '23 02:03

SoccerAnalytics26


2 Answers

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
like image 155
neilfws Avatar answered Mar 29 '23 15:03

neilfws


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)
like image 24
www Avatar answered Mar 29 '23 17:03

www