如何从R中的字符串中获得最后n个字符? 有没有像SQL的RIGHT这样的函数?
当前回答
另一种合理直接的方法是使用正则表达式和sub:
sub('.*(?=.$)', '', string, perl=T)
所以,“去掉后跟一个字符的所有东西”。为了获取更多字符,在lookahead断言中添加任意数量的圆点:
sub('.*(?=.{2}$)', '', string, perl=T)
其中。{2}表示..或“任意两个字”,意思是“去掉后跟两个字的东西”。
sub('.*(?=.{3}$)', '', string, perl=T)
对于三个字符,等等。你可以用一个变量设置要抓取的字符数,但你必须将变量值粘贴到正则表达式字符串中:
n = 3
sub(paste('.+(?=.{', n, '})', sep=''), '', string, perl=T)
其他回答
如果你不介意使用stringr包,str_sub很方便,因为你可以使用负号来向后计数:
x <- "some text in a string"
str_sub(x,-6,-1)
[1] "string"
或者,正如Max在对这个答案的评论中指出的那样,
str_sub(x, start= -6)
[1] "string"
substr的另一种替代方法是将字符串拆分为单个字符的列表并处理:
N <- 2
sapply(strsplit(x, ""), function(x, n) paste(tail(x, n), collapse = ""), N)
另一种合理直接的方法是使用正则表达式和sub:
sub('.*(?=.$)', '', string, perl=T)
所以,“去掉后跟一个字符的所有东西”。为了获取更多字符,在lookahead断言中添加任意数量的圆点:
sub('.*(?=.{2}$)', '', string, perl=T)
其中。{2}表示..或“任意两个字”,意思是“去掉后跟两个字的东西”。
sub('.*(?=.{3}$)', '', string, perl=T)
对于三个字符,等等。你可以用一个变量设置要抓取的字符数,但你必须将变量值粘贴到正则表达式字符串中:
n = 3
sub(paste('.+(?=.{', n, '})', sep=''), '', string, perl=T)
str = 'This is an example'
n = 7
result = substr(str,(nchar(str)+1)-n,nchar(str))
print(result)
> [1] "example"
>
之前有人使用了类似的解决方案,但我发现下面的想法更容易:
> text<-"some text in a string" # we want to have only the last word "string" with 6 letter
> n<-5 #as the last character will be counted with nchar(), here we discount 1
> substr(x=text,start=nchar(text)-n,stop=nchar(text))
这将产生所需的最后一个字符。