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

Seb*_*Seb 27 r substr

我需要提取字符串中的前2个字符以便稍后创建bin图分布.向量:

x <- c("75 to 79", "80 to 84", "85 to 89") 
Run Code Online (Sandbox Code Playgroud)

我已经走到这一步了:

substrRight <- function(x, n){
  substr(x, nchar(x)-n, nchar(x))
}
Run Code Online (Sandbox Code Playgroud)

调用功能

substrRight(x, 1)
Run Code Online (Sandbox Code Playgroud)

响应

[1] "79" "84" "89"
Run Code Online (Sandbox Code Playgroud)

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

[1] "75" "80" "85"
Run Code Online (Sandbox Code Playgroud)

day*_*yne 53

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

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

您还可以编写一个简单的函数来执行"反向"子字符串,假设索引从字符串的末尾开始,给出'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" 
Run Code Online (Sandbox Code Playgroud)


Ben*_*n G 10

这是一个stringr解决方案:

str_extract(x, "^.{3}")
Run Code Online (Sandbox Code Playgroud)

  • 或者: stringr::str_sub(x, start = 1, end=2) (5认同)

use*_*203 5

使用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"
Run Code Online (Sandbox Code Playgroud)