Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim a string to a specific number of characters in R

I would like to trim a character vector to the first five characters in each element. In this example I would like to trim each number in string to the first five characters. I am sure there must be an easy way to do this.

string<-
c("3243423",
"23423",
"34243234",
"2342",
"32544532",
"85678657") 

I would like to have a a vector

c("32434",
"23423",
"34243",
"2342",
"32544",
"85678")
like image 773
MatthewR Avatar asked Mar 11 '14 17:03

MatthewR


3 Answers

The following works as well (didn't know about strtrim)

substring(string, 1, 5)
like image 142
Tyler Rinker Avatar answered Nov 15 '22 05:11

Tyler Rinker


Figured it out. Hope this is helpful.

strtrim(string, 5)

like image 35
MatthewR Avatar answered Nov 15 '22 07:11

MatthewR


stri_sub function from stringi package

stri_sub("123456789",1,4)
## [1] "1234"
like image 41
bartektartanus Avatar answered Nov 15 '22 07:11

bartektartanus