Home > OS >  Get subsets between one element and the previous same element
Get subsets between one element and the previous same element

Time:02-15

Consider a vector:

vec <- c(1, 3, 4, 3, 3, 1, 1)

I'd like to get, for each element of the vector, a subset of the values in between the nth element and its previous occurrence.

The expected output is:

f(vec)

# [[1]]
# [1] 1
# 
# [[2]]
# [1] 3
# 
# [[3]]
# [1] 4
# 
# [[4]]
# [1] 3 4 3
# 
# [[5]]
# [1] 3 3
# 
# [[6]]
# [1] 1 3 4 3 3 1
# 
# [[7]]
# [1] 1 1

CodePudding user response:

We may loop over the sequence of the vector, get the index of the last match of the same element ('i1') from the previous elements of the vector and get the sequence (:) to subset the vector

lapply(seq_along(vec), function(i)  {
  i1 <- tail(which(vec[1:(i-1)] == vec[i]), 1)[1]
  i1[is.na(i1)] <- i
  vec[i1:i]
 })

-output

[[1]]
[1] 1

[[2]]
[1] 3

[[3]]
[1] 4

[[4]]
[1] 3 4 3

[[5]]
[1] 3 3

[[6]]
[1] 1 3 4 3 3 1

[[7]]
[1] 1 1
  • Related