0

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

sacvf
  • 2,463
  • 5
  • 36
  • 54

2 Answers2

1

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"
)
Forrest R. Stevens
  • 3,435
  • 13
  • 21
  • 1
    You can choose either, I like @G. Grothendieck's answer for its simplicity. I'll leave my answer because it illustrates a few things that might help others with regards to more general string and date formatting. – Forrest R. Stevens May 08 '15 at 18:18
1

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))
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341