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])
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With