Question

When I load data from a CSV file into R I receive the following data frame

dd <- data.frame(year = as.integer(c(2007,2007)),
                 doy =  as.integer(c(156,156)),
                 HHMM = as.integer(c(1200,1200)),
                 var = as.numeric(c(11.2,11.2)))

dd[,1] <- as.character(dd[,1])
dd[,2] <- as.character(dd[,2])
dd[,3] <- as.character(dd[,3])

where the first three columns are integers and the last column is numeric. I would like to convert the year, day of year, and HHMM values into one dateTime value, is that possible? The final format I am trying to get is YYYY-mm-dd HH:MM.

I can combine the year and day of year, but cannot include the HHM e.g.

strptime(paste(dd[,1], dd[,2],dd[,3]), format="%Y %j %HM") 

NA NA

How can this be done?

Was it helpful?

Solution

Try this:

# convert your separate time elements to as.POSIXct
dd$time1 <- with(dd, as.POSIXct(paste(year, doy, HHMM), format = "%Y %j %H%M"))

# convert time to character representation in desired format
dd$time2 <- with(dd, format(time1, format = "%Y-%m-%d %H:%M"))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top