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!
With paste0 and substr
ind = which(nchar(locations) == 6)
locations[ind] = paste0(substr(locations[ind], 1, 3), "0", substr(locations[ind], 4, 6))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With