Marc
Marc

Reputation: 661

R: Extract elements from a vector given start/stop positions

Is there a simple way to extract elements from a vector in R if I know the start/end indices for each extraction? For exemple I have:

v <- c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t")
start <- c(1, 4, 11, 15)
end <- c(2, 7, 11, 19)

Result should be: c("a", "b", "d", "e", "f", "g", "k", "o", "p", "q", "r", "s")

Upvotes: 3

Views: 323

Answers (4)

akrun
akrun

Reputation: 887213

We can use map2

library(purrr)
library(dplyr)
map2(start, end, ~ v[.x:.y]) %>%
       flatten_chr
#[1] "a" "b" "d" "e" "f" "g" "k" "o" "p" "q" "r" "s"

Upvotes: 1

ThomasIsCoding
ThomasIsCoding

Reputation: 101663

Maybe you can try

unlist(Map(function(x,y) v[x:y], start,end))

or

v[!!findInterval(seq_along(v),sort(c(start,end+1)))%%2]

Upvotes: 2

Daniel O
Daniel O

Reputation: 4358

another option is

unlist(sapply(1:4, function(x) v[start[x]:end[x]]))

Upvotes: 1

tmfmnk
tmfmnk

Reputation: 39858

One option could be:

v[unlist(Map(`:`, start, end))]

 [1] "a" "b" "d" "e" "f" "g" "k" "o" "p" "q" "r" "s"

Upvotes: 2

Related Questions