Home > Blockchain >  How to extract a first 3 numbers within a variable?
How to extract a first 3 numbers within a variable?

Time:01-27

My numeric variable looks like this:

u$a <- c(1234, 1432, 1456, 13467)

How do I create a new variable a1 which is the first three characters of the variable a such that it would look like this:

u$a1 <- c(123, 143, 145, 134)

Thank you.

CodePudding user response:

use integer division.

u$a1 <- u$a%/% 10^(nchar(u$a)-3)

u
#>       a  a1
#> 1  1234 123
#> 2  1432 143
#> 3  1456 145
#> 4 13467 134

CodePudding user response:

You could first convert it to a character and use substr to get the first until third character and convert it back to numeric like this:

u$a1 <- as.numeric(substr(as.character(u$a), 1, 3))
u
#>       a  a1
#> 1  1234 123
#> 2  1432 143
#> 3  1456 145
#> 4 13467 134

Created on 2023-01-26 with reprex v2.0.2


Data used:

u <- data.frame(a = c(1234, 1432, 1456, 13467))

CodePudding user response:

Using sub

u$a1 <- as.numeric(sub("^(...).*", "\\1", u$a))
  • Related