Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in R Programming by (5.3k points)

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 = '')


# [1] "leftright"

I would like to produce b, a string which is equal to the first 4 letters of a:


# [1] "left"

What should I do?

1 Answer

0 votes

To extract first(or last) n characters of a string, you can use the substr() function from the base package as follows:

a <- paste('left', 'right', sep = '')

> a

[1] "leftright"

> substr(a, 1, 4) #First four characters

[1] "left"

> substr(a, 6, 9) #Last four characters

[1] "ight"

Browse Categories