r-从每个字段中删除最后一个字符 [英] r - remove last but one character from every field

查看:1638
本文介绍了r-从每个字段中删除最后一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆