如何从R中的字符串中获得最后n个字符? 有没有像SQL的RIGHT这样的函数?
当前回答
试试这个:
x <- "some text in a string"
n <- 5
substr(x, nchar(x)-n, nchar(x))
它应该给出:
[1] "string"
其他回答
如果你不介意使用stringr包,str_sub很方便,因为你可以使用负号来向后计数:
x <- "some text in a string"
str_sub(x,-6,-1)
[1] "string"
或者,正如Max在对这个答案的评论中指出的那样,
str_sub(x, start= -6)
[1] "string"
更新:正如mdsumner所指出的,原始代码已经向量化了,因为substr是。我应该更小心的。
如果你想要一个矢量化的版本(基于Andrie的代码)
substrRight <- function(x, n){
sapply(x, function(xx)
substr(xx, (nchar(xx)-n+1), nchar(xx))
)
}
> substrRight(c("12345","ABCDE"),2)
12345 ABCDE
"45" "DE"
注意,我已经将(nchar(x)-n)更改为(nchar(x)-n+1)以获得n个字符。
str = 'This is an example'
n = 7
result = substr(str,(nchar(str)+1)-n,nchar(str))
print(result)
> [1] "example"
>
我也使用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。
之前有人使用了类似的解决方案,但我发现下面的想法更容易:
> 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))
这将产生所需的最后一个字符。