Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: How to add a zero into the middle of a string

Tags:

r

I have a dataset with locations defined by alphanumeric codes like this:

locations<-c('25N35W1', '25N36W1', '25N6W1')
presence<-c(0, 1, 0)

df<-cbind.data.frame(locations, presence)

Most of the codes have 7 digits, like the first two above, but a few of them only have six digits. I would like to add a zero after the third digit to all codes that have six digits, while leaving the seven-digit codes as they are. Does anybody know how to do this? Thanks!

like image 853
Kathryn Avatar asked Jan 26 '26 11:01

Kathryn


2 Answers

With paste0 and substr

ind = which(nchar(locations) == 6)
locations[ind] = paste0(substr(locations[ind], 1, 3), "0", substr(locations[ind], 4, 6))
like image 71
mickey Avatar answered Jan 28 '26 04:01

mickey


We can use the following regular expression to insert the 0. This has an additional advantage that it checks that the rest of your location code is in the right format:

df$locations <- sub('(?i)(\\d{2}[a-z])(\\d[a-z]\\d)', '\\10\\2', df$locations)

Output:

> df
  locations presence
1   25N35W1        0
2   25N36W1        1
3   25N06W1        0
like image 42
acylam Avatar answered Jan 28 '26 04:01

acylam



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!