Find the sequence between the elements in the vector

I would like to get a sequence between the elements in the 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 calculate the sequence between the elements 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 the R database for this task.

Expected Result

# 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
+4
source share
2 answers

We create two vectors from "ind_a", deleting the last and first observations, then we get a 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, deleting the first and last element can be done with headand tailfunction

Map(`:`, head(ind_a, -1) + 1, tail(ind_a, -1) - 1)
+4
source
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
+2

Source: https://habr.com/ru/post/1674010/


All Articles