提取字符串中的前 2 个字符

Extract the first 2 Characters in a string

我需要提取字符串中的前 2 个字符,以便稍后创建 bin plot 分布。 矢量:

x <- c("75 to 79", "80 to 84", "85 to 89") 

我已经走到这一步了:

substrRight <- function(x, n){
  substr(x, nchar(x)-n, nchar(x))
}

调用函数

substrRight(x, 1)

回应

[1] "79" "84" "89"

需要打印最后 2 个字符而不是第一个。

[1] "75" "80" "85"

你可以直接使用substr函数来取每个字符串的前两个字符:

x <- c("75 to 79", "80 to 84", "85 to 89")
substr(x, start = 1, stop = 2)
# [1] "75" "80" "85"

您还可以编写一个简单的函数来执行 "reverse" 子字符串,假设索引从字符串的末尾开始,给出 'start' 和 'stop' 值:

revSubstr <- function(x, start, stop) {
  x <- strsplit(x, "")
  sapply(x, 
         function(x) paste(rev(rev(x)[start:stop]), collapse = ""), 
         USE.NAMES = FALSE)
}
revSubstr(x, start = 1, stop = 2)
# [1] "79" "84" "89" 

使用gsub...

x <- c("75 to 79", "80 to 84", "85 to 89") 

gsub(" .*$", "", x) # Replace the rest of the string after 1st space with  nothing
[1] "75" "80" "85"

这是一个 stringr 解决方案:

stringr::str_extract(x, "^.{2}")

Returns x

的前 2 个字符

类似于@user5249203,但提取的是 number/group,而不是删除 space 之后的所有内容。在这种情况下,值可以是任意数量的连续数字。

x <- c("75 to 79", "80 to 84", "85 to 89")

sub("^(\d+) to \d+"$, "\1", x)
# [1] "75" "80" "85"

如果您想在一次调用中提取下限和上限,rematch2 concise 将每个 "named group" 放入其自己的 tibble 列中。

rematch2::re_match(x, "^(?<lower>\d+) to (?<upper>\d+)$")
# # A tibble: 3 x 4
#   lower upper .text    .match  
#   <chr> <chr> <chr>    <chr>   
# 1 75    79    75 to 79 75 to 79
# 2 80    84    80 to 84 80 to 84
# 3 85    89    85 to 89 85 to 89