r-从每个字段中删除最后一个字符 [英] r - remove last but one character from every field
问题描述
R中的substr()函数可以按位置隔离任何字符,例如
the substr() function in R can isolate any character by position e.g.
substr(df$10,2,3)
或通过使用nchar()
,可以从字段的末尾向后进行操作,以将某个字符隔离在最后一个位置,但使用以下一个来隔离字符:
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)
但是我想知道如何简单地删除数据框中列的每个字段的last but one character
.我很难做到这一点.任何帮助都会很棒!
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!
推荐答案
您可以对sub
使用正则表达式:
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.
这篇关于r-从每个字段中删除最后一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!