Trim a string to a specific number of characters in R

大兔子大兔子 提交于 2021-02-16 13:46:09

问题


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")

回答1:


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

substring(string, 1, 5)



回答2:


Figured it out. Hope this is helpful.

strtrim(string, 5)




回答3:


stri_sub function from stringi package

stri_sub("123456789",1,4)
## [1] "1234"


来源:https://stackoverflow.com/questions/22331720/trim-a-string-to-a-specific-number-of-characters-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!