Search code examples
rloopssubsetlapplysapply

Finding elements of a vector based on the numerical positions defined in another vector in R


Suppose I have the following two vectors. ll defines the number and borderlines among sets of the elements in long.

For example, here based on ll, the first two elements in long are a separate set, then the one element after those is a separate set, and so on.

I was wondering how I could automatically (perhaps as a sapply) subset each set from long based on ll?

ll <- c(2, 1, 2, 3)
long <- c(F, F, F, F, T, T, F, T)

Solution

  • You can use split to split by rep(seq_along(ll), ll) (outputs 1 1 2 3 3 4 4 4).

    split(long, rep(seq_along(ll), ll))
    
    $`1`
    [1] FALSE FALSE
    
    $`2`
    [1] FALSE
    
    $`3`
    [1] FALSE  TRUE
    
    $`4`
    [1]  TRUE FALSE  TRUE