Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding '/' to numeric values in R

Tags:

regex

r

i have numeric values that have nchar = 7 or 8.

For instance let's say I have these two values :

1234567
12345678

what I want do is:

If nchar(x) = 7

then add / after the 1st value and 3rd value.

So, my results would look like this:

1/23/4567

if nchar(x) = 8, then add / after the 2nd and 4th value. Results: 12/34/5678.

like image 585
Maya Avatar asked Jul 05 '26 02:07

Maya


2 Answers

We can use sub here:

x <- "12345678"
sub("(\\d+)(\\d{2})(\\d{4})$", "\\1/\\2/\\3", x)

Demo

like image 179
Tim Biegeleisen Avatar answered Jul 06 '26 16:07

Tim Biegeleisen


does it have to be with regex?

how about:

test <- '1234567'
n <- nchar(test)

test_split <- strsplit(test, '')[[1]]

paste0(paste0(test_split[1:(n - 6)], collapse = ''), '/',
       paste0(test_split[(n - 5):(n - 4)], collapse = ''), '/',
       paste0(test_split[(n - 3):n], collapse = ''))
like image 21
DS_UNI Avatar answered Jul 06 '26 15:07

DS_UNI



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!