Extract the first 2 Characters in a string

You can just use the substr function directly to take the first two characters of each string:

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

You could also write a simple function to do a "reverse" substring, giving the 'start' and 'stop' values assuming the index begins at the end of the string:

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" 

Here's a stringr solution:

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

Returns first 2 characters of x


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

Tags:

R

Substr