sacvf
sacvf

Reputation: 2533

How to convert from numeric to format of dates and time?

I have one text file that look like:

wd <- read.table("C:\\Users\\value.txt", sep ='' , header =TRUE)
head(wd) # hourly values
#   Year day hour mint   valu1          
# 1 2002   1    7   30     0.5     
# 2 2002   1    8    0     0.3     
# 3 2002   1    8   30     0.4     

I want to add another column with format od date like this:

"2002-01-01 07:30:00 UTC"

Thanks for your help

Upvotes: 0

Views: 70

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 269371

Try this. No packages are used:

transform(wd, 
   Date = as.POSIXct(paste(Year, day, hour, mint), format = "%Y %j %H %M", tz = "UTC")
)
##   Year day hour mint valu1                Date
## 1 2002   1    7   30   0.5 2002-01-01 07:30:00
## 2 2002   1    8    0   0.3 2002-01-01 08:00:00
## 3 2002   1    8   30   0.4 2002-01-01 08:30:00

Note: Input is:

wd <- structure(list(Year = c(2002L, 2002L, 2002L), day = c(1L, 1L, 
1L), hour = c(7L, 8L, 8L), mint = c(30L, 0L, 30L), valu1 = c(0.5, 
0.3, 0.4)), .Names = c("Year", "day", "hour", "mint", "valu1"
), class = "data.frame", row.names = c(NA, -3L))

Upvotes: 1

Forrest R. Stevens
Forrest R. Stevens

Reputation: 3485

You might be able to simplify things with a package like lubridate but I think to illustrate the solution this will work for you. Next time it would save time for people answering if you provide code to create the sample data like I've done here.

d <- read.table(header=T, stringsAsFactors=F, text="
Year day hour mint   valu1          
2002   1    7   30     0.5     
2002   1    8    0     0.3     
2002   1    8   30     0.4
")

require(stringr)

d$datetime <- strptime(
  paste0(
    d$Year, "-", 
    str_pad(d$day,3,pad="0"), 
    str_pad(d$hour,2,pad="0"), 
    ":", 
    str_pad(d$mint, 2, pad="0")
  ), 
  format="%Y-%j %H:%M"
)

Upvotes: 1

Related Questions