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

R 提取字符串中的前2个字符,r,substr,R,Substr,我需要提取字符串中的前2个字符,以便稍后创建bin plot分布。 向量: 回应 [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" x使用gsub x <- c("7

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

回应

[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"

x使用
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"

x这里有一个
stringr
解决方案:

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

返回
x

的前两个字符,类似于@user5249203,但提取一个数字/组,而不是删除空格后的所有字符。在这种情况下,值可以是任意数量的连续数字

x或:stringr::str_sub(x,开始=1,结束=2)
x <- c("75 to 79", "80 to 84", "85 to 89")
substr(x, start = 1, stop = 2)
# [1] "75" "80" "85"
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" 
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::str_extract(x, "^.{2}")