Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract the first (or last) n characters of a string

Tags:

string

r

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?

like image 322
Lisa Ann Avatar asked Apr 09 '13 08:04

Lisa Ann


People also ask

How do I get the first n characters of a string in Excel?

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.

How do I get the last 4 characters of a string in Excel?

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.

How do I get the last 4 characters of a string in R?

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.


2 Answers

See ?substr

R> substr(a, 1, 4) [1] "left" 
like image 64
rcs Avatar answered Oct 08 '22 05:10

rcs


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" 
like image 34
juba Avatar answered Oct 08 '22 05:10

juba