从R中的字符串中提取最后n个字符 [英] Extracting the last n characters from a string in R
本文介绍了从R中的字符串中提取最后n个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从 R 中的字符串中获取最后 n 个字符?有没有类似 SQL 的 RIGHT 的函数?
How can I get the last n characters from a string in R? Is there a function like SQL's RIGHT?
推荐答案
我不知道 base R 中的任何内容,但使用 substr
和nchar
:
I'm not aware of anything in base R, but it's straight-forward to make a function to do this using substr
and 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 指出的那样,这是矢量化的.考虑:
This is vectorised, as @mdsumner points out. Consider:
x <- c("some text in a string", "I really need to learn how to count")
substrRight(x, 6)
[1] "string" " count"
这篇关于从R中的字符串中提取最后n个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文