I have this vector:
1 2 19 5 7 2 20 56 89 20 103 76 104
How can I remove 1 to the highest of each pair of consecutive values (in this case: 1-2, 19-20, 103-104), while maintaining the rest of the values unaltered?
1 1 19 5 7 1 19 56 89 19 103 76 103
Thanks!
CodePudding user response:
Sort the values, get the index for consecutive values, and remove 1:
x <- c(1, 2, 19, 5, 7, 2, 20, 56, 89, 20, 103, 76, 104)
sorted <- sort(x)
w <- sorted[which(diff(sorted) == 1)] 1
x[x %in% w] <- x[x %in% w] - 1
# [1] 1 1 19 5 7 1 19 56 89 19 103 76 103