如何从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"
推荐文章
- 我应该如何从字符串中删除所有的前导空格?- - - - - -斯威夫特
- 使用该集合的原因。种子功能
- 将整数转换为字符串,以逗号表示千
- 将JavaScript字符串中的多个空格替换为单个空格
- 加快R中的循环操作
- printf()和puts()在C语言中的区别是什么?
- jQuery -替换字符串中某个字符的所有实例
- Base64长度计算?
- 使用split("|")按管道符号拆分Java字符串
- 错误:无法找到函数…在R
- Std::cin输入空格?
- 在编写自己的函数时,如何使用R的省略号特性?
- 当我的ggplot2语法合理时,我如何处理R CMD检查“全局变量无可见绑定”注释?
- 我如何在c++中创建一个随机的字母数字字符串?
- 如何使用JavaScript大写字符串中每个单词的第一个字母?