简体   繁体   中英

How to extract a first 3 numbers within a variable?

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.

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

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))

Using sub

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM