0 votes
1 view
in R Programming by (5k 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 = '')

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?

1 Answer

0 votes
by (24.7k points)

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"

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...