Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subsetting over a vector with another vector

Say I have a vector like

vector = c('hello','world')

and another two vectors like

vector2 = c(2,4)
vector3 = c(4,5)

How could I create a fourth vector that is the subset of each element in the first vector by the other two vectors? Something like

vector[1][vector2[1]:vector3[1]]

so for these vectors it would be

vector4 = ('ell','ld')

I've tried to use sapply but ran into a roadblock since I wasn't sure how I could write the function to subset them.

vector4 = sapply(vector, function(x) x[vector2:vector3])
like image 226
ThatsNotMyName Avatar asked Sep 11 '26 04:09

ThatsNotMyName


1 Answers

This is covered by substr/substring, which will iterate over each input:

substr(vector, vector2, vector3)
substring(vector, vector2, vector3)
#[1] "ell" "ld" 

The two functions are slightly different. substring will extend to whichever input is longer and recycle:

substring(c("hello","nopes"), 1:3, 2:4)
#[1] "he" "op" "ll"
substr(c("hello","nopes"), 1:3, 2:4)
#[1] "he" "op"

This can be particularly useful when you want to extract multiple substrings from a single string:

substring("hello", 1:3, 2:4)
#[1] "he" "el" "ll"
substr("hello", 1:3, 2:4)
#[1] "he"
like image 55
thelatemail Avatar answered Sep 12 '26 17:09

thelatemail



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!