I want to extract the first (or last) n characters of a string. This would be the equivalent to Excel's LEFT()
and RIGHT()
. A small example:
# create a string a <- paste('left', 'right', sep = '') a # [1] "leftright"
I would like to produce b
, a string which is equal to the first 4 letters of a
:
b # [1] "left"
What should I do?
Extract first n characters from string Select a blank cell, here I select the Cell G1, and type this formula =LEFT(E1,3) (E1 is the cell you want to extract the first 3 characters from), press Enter button, and drag fill handle to the range you want. Then you see the first 3 characters are extracted.
Select a cell that used to place the extracted substring, click Kutools > Formula Helper > Text > Extract strings between specified text. 2. In the Formulas Helper dialog, go to the Arguments input section, then select or directly type the cell reference and the two characters you want to extract between.
To get the last n characters from a string, we can use the stri_sub() function from a stringi package in R. The stri_sub() function takes 3 arguments, the first one is a string, second is start position, third is end position.
See ?substr
R> substr(a, 1, 4) [1] "left"
The stringr
package provides the str_sub
function, which is a bit easier to use than substr
, especially if you want to extract right portions of your string :
R> str_sub("leftright",1,4) [1] "left" R> str_sub("leftright",-5,-1) [1] "right"
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