Reputation: 12723
I would like to get the sequence between elements in a vector. Here is a reproducible example.
vec <- c( 'a', letters[2:7], 'a', letters[9:14], 'a', letters[16:21] ) # sample data
ind_a <- which( grepl( 'a', vec )) # indices matching the character 'a'
ind_a <- c( ind_a, length(vec)+1 ) # concatenate the length of 'vec' + 1 with indices
ind_a
# [1] 1 8 15 22
Now, how to compute the sequence between the elements of ind_a
. For example, seq(from = 2, to = 7, by = 1)
and the same for others.
Preferably, I would like to know any function in base R for this task.
Expected Output
# List of 3
# $ : int [1:6] 2 3 4 5 6 7
# $ : int [1:6] 9 10 11 12 13 14
# $ : int [1:6] 16 17 18 19 20 21
Upvotes: 4
Views: 812
Reputation: 32558
lapply(2:length(ind_a), function(i) setdiff(sequence(ind_a[i] - 1), sequence(ind_a[i-1])))
#OR
lapply(2:length(ind_a), function(i) (ind_a[i-1]+1):(ind_a[i]-1))
#[[1]]
#[1] 2 3 4 5 6 7
#[[2]]
#[1] 9 10 11 12 13 14
#[[3]]
#[1] 16 17 18 19 20 21
Upvotes: 2
Reputation: 887951
We create two vectors from 'ind_a' by removing the last and first observations, then get the sequence of corresponding elements with Map
Map(seq, ind_a[-length(ind_a)]+1, ind_a[-1]-1)
#[[1]]
#[1] 2 3 4 5 6 7
#[[2]]
#[1] 9 10 11 12 13 14
#[[3]]
#[1] 16 17 18 19 20 21
Or as @Zelazny7 suggested, removing the first and last element can be done with head
and tail
function
Map(`:`, head(ind_a, -1) + 1, tail(ind_a, -1) - 1)
Upvotes: 4