r - Identify and replace duplicate from a column vector -
this question has answer here:
i've got 2 columns under:
a<- c(1,1,1,2,3,2,2,2,2,1,0,0,0,0,2,3,4,4,1,1) date<- sys.date()-20:1 data<- xts(a,date) colnames(data)<- "a" data here can see there lot of duplicate elements, ie. repeated ones. want code can replace elements consecutive , duplicate 0 except first element. result require
a<- c(1,0,0,2,3,2,0,0,0,1,0,0,0,0,2,3,4,0,1,0) i've tried i've learnt earlier post
ifelse(data$a == c(data$a[1]-1,data$a[(1:length(data$a)-1)]) , 0 , data$a) and i've tried
data$a<- replace(data$a, duplicated(c(0, cumsum(abs(diff(data$a))))), 0) but both codes not working in xts. though both above mentioned code working normal vector.
you on right track diff, think it's simpler you're making it:
a[c(f, diff(a) == 0)] <- 0 [1] 1 0 0 2 3 2 0 0 0 1 0 0 0 0 2 3 4 0 1 0 edit
to make solution column, can assign by:
data$b <- ifelse(c(f, diff(data$a)==0), 0, data$a) or making copy:
data$b <- data$a data$b[c(f, diff(data$b) ==0)] <- 0
Comments
Post a Comment