简体   繁体   中英

transforming & adding new column in r

I have currently have a data frame that is taken from a data feed of events that happened in chronological order. I would like to add a new column onto to each row of my data the corresponds to the previous event's endx if the prior event type is 1 & the previous event's x if the prior event type is not 1

eg

player_id <- c(12, 17, 26, 3)
event_type <- c(1, 3, 1, 10)
x <- c(65, 34, 43, 72)
endx <- c(68, NA, 47, NA)
df <- data.frame(player_id, event_type, x, endx)
df
     player_id  event_type  x  endx
1        12          1      65   68
2        17          3      34   NA
3        26          1      43   47
4         3         10      72   NA

so end result

  player_id event_type   x     endx  previous
1        12          1   65     68     NA
2        17          3   34     NA     68
3        26          1   43     47     34 
4         3         10   72     NA     47

We can use if_else

library(dplyr)
df %>% 
    mutate(previous = if_else(lag(event_type)==1, lag(endx), lag(x)))
#    player_id event_type  x endx previous
#1        12          1 65   68       NA
#2        17          3 34   NA       68
#3        26          1 43   47       34
#4         3         10 72   NA       47

I am sure this isn't the most succient way but you can use a loop and indexing.

df$previous <- NA
for( i in 2: nrow(df)){
df[ i  , "previous"] <- df[ i-1 , "endx"]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM