0

I'm new to R, but need help formatting just one variable in my data frame:

> str(g.2015.1990$START.TIME)
 int [1:60464] 712 606 1238 708 709 707 407 707 612 1237 ...

Although R interprets this as an integer, it is a time variable formatted in 3-4 digits (HMM or HHMM depending on the time, where "Hour" ranges from 1:12, not 1:24) with no date attached (although there is a separate variable for date that corresponds with each time). I've read all related posts, googled everything I can think of, watched every YouTube video I could find, and even went out and bought "R for Dummies;" but, nothing has worked. Here is a fraction of the codes I've tried:

timex <- mapply(function(x, y) paste0(rep(x, y), collapse = ""), 0, 4 - nchar(g.2015.1990$START.TIME))
timexx <- paste0(timex, g.2015.1990$START.TIME)
timexxx = format(strptime(timexx, format="%H%M"), format = "%H:%M")
timex = format(as.POSIXct(sprintf("%004.0f",g.2015.1990$START.TIME),format="%H%M"),"%H:%M")
timex = format(strptime(g.2015.1990$START.TIME,"%H%M"),"%H:%M")
timex <- gsub("([0-9]{3})","0\\1",g.2015.1990$START.TIME)
timexx = format(strptime("g.2015.1990$START.TIME","%H%M%S"),"%H:%M:%S")
timex = as.numeric(g.2015.1990$START.TIME)
timex = if(g.2015.1990$START.TIME) < 4 nchar(g.2015.1990$START.TIME) + 1
timex = as.Date(origin = g.2015.1990$START.TIME, format = "%H%M")
timex = as.POSIXct(as.character(g.2015.1990$START.TIME))
timex = strptime("g.2015.1990$DATE, g.2015.1990$START.TIME", "%y%m%d, %H%M")
timex = strftime("g.2015.1990$START.TIME", "%H%M")
timex = as.POSIXct(g.2015.1990$START.TIME, format="%H:%M")
timex = times(paste0("00", as.character(g.2015.1990$START.TIME)))
timex = strptime(g.2015.1990$START.TIME, "%I%M")
timex = as.POSIXlt(g.2015.1990$START.TIME, format = "%I%M", origin = "g.2015.1990$START.TIME")
timex = as.POSIXlt(as.character(g.2015.1990$START.TIME), format = "%I%M")

(Where "timex" is a stand in for the variable in question, so as not to mess up my data)

Some of these are sequences and some are single-lines of code. I can't even keep it straight anymore. Your help is VERY much appreciated.

  • you could try: `strptime(sprintf('%s %04d', Sys.Date(), starttime), '%Y-%m-%d %H%M')` – Jaap Jul 20 '16 at 15:20
  • Hey it worked! I wish I understood this code better. I'd like to replace Sys.Date() with the variable in my data set for date so as to link the time to the appropriate date rather than today's date. However, while doing this was largely successful, it did produce some NAs. Any suggestions on how to do this? – Brandon McCormick Jul 20 '16 at 19:57
  • Nvm, the problem described above was the consequence of my date variable. It's producing NAs for the years 2000-2009 because the 0s make it no longer in the two-digit, %y format. – Brandon McCormick Jul 21 '16 at 00:11

0 Answers0