R 截取开头或结尾的子字符串

2022-06-18

有两种方法可以实现,R 截取开头或结尾的子字符串。分别是:

  1. base R, substr
  2. stringr, str_sub, 支持负号索引,来截取字符结尾的字符串

substr

x <- "this is an example"                  # Create example character string

substr(x, 1, 3)                            # 截取前3个字符
# "thi"

n_last <- 3                                # Specify number of characters to extract
substr(x, nchar(x) - n_last + 1, nchar(x)) # 截取后3个字符
# "ple"

stringr::str_sub

stringr::str_sub(x, - 3, - 1)                       # Extract last characters with str_sub
# "ple"

Reference

[Extract First or Last n Characters from String in R (3 Examples) Get Leading & Trailing Chars](https://statisticsglobe.com/r-extract-first-or-last-n-characters-from-string)