'Replace character values with time values in R
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?
Solution 1:[1]
Try
df$time=sprintf("%04d",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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user2974951 |
