如何从R中的字符串中获得最后n个字符? 有没有像SQL的RIGHT这样的函数?
当前回答
substr的另一种替代方法是将字符串拆分为单个字符的列表并处理:
N <- 2
sapply(strsplit(x, ""), function(x, n) paste(tail(x, n), collapse = ""), N)
其他回答
一个简单的基于R的解决方案,使用substring()函数(谁知道这个函数甚至存在?)
RIGHT = function(x,n){
substring(x,nchar(x)-n+1)
}
这基本上利用了substr()在下面的优势,但其默认结束值为1,000,000。
例子:
> RIGHT('Hello World!',2)
[1] "d!"
> RIGHT('Hello World!',8)
[1] "o World!"
如果你不介意使用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)
以防万一,如果需要选择一系列字符:
# For example, to get the date part from the string
substrRightRange <- function(x, m, n){substr(x, nchar(x)-m+1, nchar(x)-m+n)}
value <- "REGNDATE:20170526RN"
substrRightRange(value, 10, 8)
[1] "20170526"
之前有人使用了类似的解决方案,但我发现下面的想法更容易:
> 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))
这将产生所需的最后一个字符。