0

I have a vector of strings a<-data.table(value=("001","01")) that really should be decimals (0.01 and 0.1) and would liked to split the strings at the first 0 and add in a decimal before it.

I can split the string and get a list

A<-strsplit(a$value, "(?=[0])", perl = TRUE)

so I can envisage doing paste0(x[[1]][1],".",x[[1]][2]) inside a function but I'm getting a bit stuck with how to refer to the indices:

dFun<-function(){
  as.numeric(paste0(x[[1]][1],".",x[[1]][2]))
}


purrr::map_df(.x=1:2,.f=dFun)

Any pointers would be much appreciated.

HCAI
  • 2,213
  • 8
  • 33
  • 65

3 Answers3

2

Maybe you can try this

> a[, value := gsub("(?=1)", ".", value, perl = TRUE)][]
   value
1:  00.1
2:   0.1

or

> a[, value := sub("(^0)", "\\1.", value)][]
   value
1:  0.01
2:   0.1

or

> a[, value := as.numeric(sub("(^0)", "\\1.", value))][]
   value
1:  0.01
2:  0.10
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
  • Thomas thank you very much indeed to looking at this so quickly. As you have already spotted, I made a mistake with the splitting. – HCAI Aug 10 '21 at 10:04
  • @HCAI Yes, I see that. You can check my answer, which may include the one you want. – ThomasIsCoding Aug 10 '21 at 10:05
2

Since sub will replace only first occurrence, you can do -

library(data.table)

a <- data.table(value=c("001","01"))
a[, value := as.numeric(sub('0', '0.', value))]
a

#   value
#1:  0.01
#2:  0.10
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
2

With str_replace

library(stringr)
a[, value := as.numeric(str_replace(value, '0', '0.'))]
> a
   value
1:  0.01
2:  0.10

`

akrun
  • 874,273
  • 37
  • 540
  • 662