Put decimal separator after the first two digits in R

45 Views Asked by At

I have downloaded a table of temperature data from a datalogger where the decimal points dissapeared. Here is a fragment:

temperature<-c( 227725, 208957, 210834, 214588, 218342)
date<-c("2022-06-14 12:02:01 UTC", "2022-06-14 12:32:01 UTC", "2022-06-14 13:02:01 UTC", "2022-06-14 13:32:01 UTC", "2022-06-14 14:02:01 UTC")

df<-data.frame(date,temperature)


df
                     date temperature
1 2022-06-14 12:02:01 UTC      227725
2 2022-06-14 12:32:01 UTC      208957
3 2022-06-14 13:02:01 UTC      210834
4 2022-06-14 13:32:01 UTC      214588
5 2022-06-14 14:02:01 UTC      218342

I already know that the decimal point should be after the first two digits.

Is there a way to insert the decimal separator?

Thanks in advance!

2

There are 2 best solutions below

0
shaun_m On BEST ANSWER

If the numbers may not be all six-digit but you are sure that the decimal point must come after the second digit, then the following should work:

  1. convert to character as.character(df$temperature
  2. use gsub to replace the first 2 digits with themselves plus a dot gsub("^(\\d{2})", "\\1.", as.character(df$temperature))
  3. convert back to a number as.numeric(gsub("^(\\d{2})", "\\1.", as.character(df$temperature)))

So,

df$temperature <- as.numeric(gsub("^(\\d{2})", "\\1.", as.character(df$temperature)))

print(df)
                     date temperature
1 2022-06-14 12:02:01 UTC     22.7725
2 2022-06-14 12:32:01 UTC     20.8957
3 2022-06-14 13:02:01 UTC     21.0834
4 2022-06-14 13:32:01 UTC     21.4588
5 2022-06-14 14:02:01 UTC     21.8342
0
Onyambu On

Another base R solution:

transform(df, temperature = temperature * 10 ^(2 - nchar(temperature)))

                     date temperature
1 2022-06-14 12:02:01 UTC     22.7725
2 2022-06-14 12:32:01 UTC     20.8957
3 2022-06-14 13:02:01 UTC     21.0834
4 2022-06-14 13:32:01 UTC     21.4588
5 2022-06-14 14:02:01 UTC     21.8342