I have a matrix like
[,1] [,2]
[1,] 1 3
[2,] 4 6
[3,] 11 12
[4,] 13 14
I want to convert this matrix to a vector
Throwing this one here, it uses base R and should be somewhat fast since the inevitable loop is handled by rep:
zero.lengths <- m[,1] - c(0, head(m[,2], -1)) - 1
one.lengths <- m[,2] - m[,1] + 1
rep(rep(c(0, 1), nrow(m)),
as.vector(rbind(zero.lengths, one.lengths)))
Or another solution using sequence:
out <- integer(m[length(m)]) # or `integer(20)` following OP's edit.
one.starts <- m[,1]
one.lengths <- m[,2] - m[,1] + 1
one.idx <- sequence(one.lengths) + rep(one.starts, one.lengths) - 1L
out[one.idx] <- 1L