如何从R中的字符串中获得最后n个字符? 有没有像SQL的RIGHT这样的函数?
当前回答
我不知道base R中的任何东西,但它是直接使用substr和nchar创建一个函数来做到这一点:
x <- "some text in a string"
substrRight <- function(x, n){
substr(x, nchar(x)-n+1, nchar(x))
}
substrRight(x, 6)
[1] "string"
substrRight(x, 8)
[1] "a string"
正如@mdsumner指出的那样,这是向量化的。考虑:
x <- c("some text in a string", "I really need to learn how to count")
substrRight(x, 6)
[1] "string" " count"
其他回答
我也使用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。
以防万一,如果需要选择一系列字符:
# 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))
这将产生所需的最后一个字符。
我不知道base R中的任何东西,但它是直接使用substr和nchar创建一个函数来做到这一点:
x <- "some text in a string"
substrRight <- function(x, n){
substr(x, nchar(x)-n+1, nchar(x))
}
substrRight(x, 6)
[1] "string"
substrRight(x, 8)
[1] "a string"
正如@mdsumner指出的那样,这是向量化的。考虑:
x <- c("some text in a string", "I really need to learn how to count")
substrRight(x, 6)
[1] "string" " count"
使用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")
安装此包。