I have a data frame like the following:
library(data.table)
set.seed(1234)
DT<-data.table(x=c("a","a","a","b","b","c","c","c","d","d","d","d"),v=sample(1:4,12,replace = T))
x v
a 1
a 3
a 3
b 3
b 4
c 3
c 1
c 1
d 3
d 3
d 3
d 3
What I need to do is to replace the value "v" conditionally, each time the variable "x" changes, like so:
x v
a 1
a 3
a 3
b NA
b 4
c NA
c 1
c 1
d NA
d 3
d 3
d 3
Am I bound to do a loop or there is a one liner to do the same thing? Thanks!