r - remove last but one character from every field

北城以北 提交于 2019-12-25 07:17:16

问题


the substr() function in R can isolate any character by position e.g.

substr(df$10,2,3)

or by using nchar() it is possible to work backwards from the end of the field to isolate a character in a position such as last but one using:

substr(df$10,nchar(df$10)-2,nchar(df$10)-1)

however I would like to know how to simply remove the last but one character of every field for a column in a dataframe. I am having difficulty doing this. any help would be great!


回答1:


You can use a regular expression with sub:

x <- c("banana","republic")
sub(".(.)$","\\1",x)
[1] "banaa"   "republc"

What this does is match the last two characters in a string, and replace them with only the last one, which is captured in a capture group.



来源:https://stackoverflow.com/questions/36796752/r-remove-last-but-one-character-from-every-field

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