dataframe - R and dplyr : how to use values from a previous row and column -
i trying create new variable function of previous rows , columns. have found lag() function in dplyr can't accomplish like.
library(dplyr) x = data.frame(replicate(2, sample(1:3,10,rep=true))) x1 x2 1 1 3 2 2 3 3 2 2 4 1 3 5 2 3 6 2 1 7 3 2 8 1 1 9 1 3 10 2 2 x = mutate(x, new_col = # if x2==1, value of x1 in previous row, # if x2!=1, 0))
my best attempt:
foo = function(x){ if (x==1){ return(lag(x1)) }else{ return(0) } x = mutate(x, new_col=foo(x1))
we can use ifelse
x %>% mutate(newcol = ifelse(x2==1, lag(x1), 0))
Comments
Post a Comment