We can use rleid
from data.table
. We loop over each unique number and find it's first and last occurrence in the original sequence and convert it into data.frame.
library(data.table)
indx <- rleid(A)
new_dat <- data.frame(t(sapply(unique(indx), function(x) {
val <- which(indx == x)
c(start = min(val), stop = max(val))
})))
transform(new_dat, value = A[new_dat$start])
# X1 X2 value
#1 1 5 1
#2 6 10 0
#3 11 15 2
#4 16 20 -1
When the numbers are repeating
A <- c(1,1,1,1,1,0,0,0,0,0,2,2,2,2,2,-1,-1,-1,-1,-1, 1, 1, 1)
indx <- rleid(A)
new_dat <- data.frame(t(sapply(unique(indx), function(x) {
val <- which(indx == x)
c(start = min(val), stop = max(val))
})))
transform(new_dat, value = A[new_dat$start])
# start stop value
#1 1 5 1
#2 6 10 0
#3 11 15 2
#4 16 20 -1
#5 21 23 1
A better concise data.table
way suggested by @Henrik
library(data.table)
data.table(A)[ , .(from = .I[1], to = .I[.N], val = A[1]), by = rleid(A)][,-1]
# from to val
#1: 1 5 1
#2: 6 10 0
#3: 11 15 2
#4: 16 20 -1
#5: 21 23 1