8

How to select first 2 digits of a number? I just need the name of the function

Example: 12455 turns into 12, 13655 into 13

Basically it's the equivalent of substring for integers.

zx8754
  • 52,746
  • 12
  • 114
  • 209

2 Answers2

8

If at the end you need again a numeric vector/element, you can use

as.numeric(substr(x, 1, 2))
Ric S
  • 9,073
  • 3
  • 25
  • 51
  • 1
    You're right, I used `as.character` because in the docs is written that `substr` wants a character vector, but actually the function uses `as.character` internally. I edit my answer in order to use less code. Thank you @DarrenTsai – Ric S May 22 '20 at 14:59
4

This solution uses gsub, the anchor ^ signifiying the start position of a string, \\d{2} for any two digits appearing at this position, wrapped into (...) to mark it as a capturing group, and backreference \\1 in the replacement argument, which 'recalls' the capturing group:

x <- c(12455,13655)

gsub("(^\\d{2}).*", "\\1", x)
[1] "12" "13"

Alternatively, use str_extract:

library(stringr)
str_extract(x, "^\\d{2}")
Chris Ruehlemann
  • 20,321
  • 4
  • 12
  • 34