Reputation: 23607
I have a vector of strings:
v.string <- c('abc', 'beb', 'lol', 'heh', 'hah')
Is there a way of extracting the first N elements from the vector? So in the above if I want to extract the first 2, i will get:
'ab','be','lo','he','ha'
Or do I have to do a loop and use substr
function? My vector is rather long.
Thanks
Upvotes: 5
Views: 5122
Reputation: 6124
you are looking for ?substr
substr( v.string , start = 1 , stop = 2 )
(incorporating @Arun's comment) if you want to start at the second-to-last letters, you might also use the nchar
function, so
# print the number of characters in each string in your character vector..
nchar( v.string )
# ..which gets used to..
# print the second-to-last character until the end of the string
substr( v.string , start = nchar( v.string ) - 1 , stop = nchar( v.string ) )
Upvotes: 11