如何从R中的字符串中获得最后n个字符? 有没有像SQL的RIGHT这样的函数?


当前回答

使用stringi包中的stri_sub函数。 要从末尾获得子字符串,请使用负数。 请看下面的例子:

stri_sub("abcde",1,3)
[1] "abc"
stri_sub("abcde",1,1)
[1] "a"
stri_sub("abcde",-3,-1)
[1] "cde"

你可以从github: https://github.com/Rexamine/stringi安装这个包

它是可在CRAN现在,简单的类型

install.packages("stringi")

安装此包。

其他回答

我也使用substr,但方式不同。我想提取“给我你的食物”的最后6个字符。以下是步骤:

(1)拆分字符

splits <- strsplit("Give me your food.", split = "")

(2)提取最后6个字符

tail(splits[[1]], n=6)

输出:

[1] " " "f" "o" "o" "d" "."

每个字符都可以通过分割[[1]][x]访问,其中x是1到6。

substr的另一种替代方法是将字符串拆分为单个字符的列表并处理:

N <- 2
sapply(strsplit(x, ""), function(x, n) paste(tail(x, n), collapse = ""), N)

之前有人使用了类似的解决方案,但我发现下面的想法更容易:

> 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))

这将产生所需的最后一个字符。

我使用下面的代码来获取字符串的最后一个字符。

    substr(output, nchar(stringOfInterest), nchar(stringOfInterest))

您可以使用nchar(stringOfInterest)来计算如何获取最后几个字符。

试试这个:

x <- "some text in a string"
n <- 5
substr(x, nchar(x)-n, nchar(x))

它应该给出:

[1] "string"