Home > Blockchain >  Replace character values with time values in R
Replace character values with time values in R

Time:01-28

I'm working with a public data base os meteorological data. I wish to replace "character" values "0", "100", "200" to 00:00, 01:00, 02:00 time format. Data is as follow:

head(brazlandia, n = 24)
         date time temp
1  2022-01-01    0   NA
2  2022-01-01  100 19.1
3  2022-01-01  200   NA
4  2022-01-01  300 18.8
5  2022-01-01  400 18.8
6  2022-01-01  500 18.6
7  2022-01-01  600 18.4
8  2022-01-01  700 18.4
9  2022-01-01  800 18.3
10 2022-01-01  900 18.4
11 2022-01-01 1000 18.7

I wish they were:

head(brazlandia, n = 24)
         date time temp
1  2022-01-01 00:00   NA
2  2022-01-01 01:00 19.1
3  2022-01-01 02:00   NA
4  2022-01-01 03:00 18.8
5  2022-01-01 04:00 18.8
6  2022-01-01 05:00 18.6
7  2022-01-01 06:00 18.4
8  2022-01-01 07:00 18.4
9  2022-01-01 08:00 18.3
10 2022-01-01 09:00 18.4
11 2022-01-01 10:00 18.7

How can I do it withou one to one replacement code lines?

CodePudding user response:

Try

df$time=sprintf("d",df$time)
df$time=paste0(substr(df$time,1,2),":",substr(df$time,3,4))

         date  time temp
1  2022-01-01 00:00   NA
2  2022-01-01 01:00 19.1
3  2022-01-01 02:00   NA
4  2022-01-01 03:00 18.8
5  2022-01-01 04:00 18.8
6  2022-01-01 05:00 18.6
7  2022-01-01 06:00 18.4
8  2022-01-01 07:00 18.4
9  2022-01-01 08:00 18.3
10 2022-01-01 09:00 18.4
11 2022-01-01 10:00 18.7

CodePudding user response:

df$time <- gsub("(.{2})(.{2})", "\\1:\\2", sprintf("d", df$time))

or

df$time <- paste(sprintf("d", df$time/100), "00", sep = ":") # if all are complete hours

df$time <- paste(sprintf("d", df$time %/% 100), sprintf("d", df$time %% 100), sep = ":") # works with minutes too like 2210 becomes 22:10
  •  Tags:  
  • Related