Extract the first 2 Characters in a string

Seb picture Seb · Aug 3, 2016 · Viewed 101.7k times · Source

I need to extract the 1st 2 characters in a string to later create bin plot distribution. vector:

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

I have gotten this far:

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

invoke function

substrRight(x, 1)

Response

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

Need to prints the last 2 characters not the first.

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

Answer

dayne picture dayne · Aug 3, 2016

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"