79

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

4 Answers 4

122

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" 
0
38

Here's a stringr solution:

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

Returns first 2 characters of x

3
  • 5
    Or: stringr::str_sub(x, start = 1, end=2)
    – Aran
    Jul 10, 2020 at 12:54
  • Hi, what if i want only 2 digits after the asterisk symbol? for example A*42:09 or ABD*24:87. Aug 17, 2021 at 3:14
  • You probably need an anchor, something like ""(?<=\*){2}"
    – Ben G
    Aug 17, 2021 at 18:51
6

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

Similar to @user5249203, but extracts a number/group, instead of removing everything after the space. In this case, the values can be any number of consecutive digits.

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

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

If you wanted to extract the lower & upper bound in one call, rematch2 concise places each "named group" into its own tibble column.

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.