Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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")

like image 385
Marc Avatar asked Jun 28 '26 04:06

Marc


1 Answers

One option could be:

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

 [1] "a" "b" "d" "e" "f" "g" "k" "o" "p" "q" "r" "s"
like image 50
tmfmnk Avatar answered Jun 29 '26 17:06

tmfmnk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!