R从字符串中删除第一个字符 [英] R remove first character from string

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

问题描述

我可以从字符串中删除最后一个字符:

I can remove the last character from a string:

listfruit  <- c("aapplea","bbananab","oranggeo")
gsub('.{1}$', '', listfruit)

但是我在尝试从字符串中删除第一个字符时遇到问题.还有第一个和最后一个字符.如果您提供帮助,我将不胜感激.

But I am having problems trying to remove the first character from a string. And also the first and last character. I would be grateful for your help.

推荐答案

如果我们需要去掉第一个字符,使用sub,匹配一个字符(.代表一个单个字符),将其替换为 ''.

If we need to remove the first character, use sub, match one character (. represents a single character), replace it with ''.

sub('.', '', listfruit)
#[1] "applea"  "bananab" "ranggeo"

或者对于第一个和最后一个字符,匹配字符串开头(^.)或字符串结尾(.$)的字符并替换它带有 ''.

Or for the first and last character, match the character at the start of the string (^.) or the end of the string (.$) and replace it with ''.

gsub('^.|.$', '', listfruit)
#[1] "apple"  "banana" "rangge"

我们也可以将其作为一个组捕获并替换为反向引用.

We can also capture it as a group and replace with the backreference.

sub('^.(.*).$', '\\1', listfruit)
#[1] "apple"  "banana" "rangge"

<小时>

另一个选项是 substr

substr(listfruit, 2, nchar(listfruit)-1)
#[1] "apple"  "banana" "rangge"

这篇关于R从字符串中删除第一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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