function to extract first 2 digits of 5 digits numbers within a dataframe in r

Viewed 14248

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.

2 Answers

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

as.numeric(substr(x, 1, 2))

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}")
Related