0

I am stuck combining two columns of a data frame into one. Below is the code to reproduce the problem

df <- data.frame(date = c("2/13/1962 0:00:00", "4/13/1972 0:00:00", "3/13/1982 0:00:00", "12/13/1992 0:00:00"), 
                 time = c("0900", "1000", "1101", "1603"))

#This works
df$tmp <- as.Date(df$date, format="%m/%d/%Y")
df  

                date     time        tmp  
    1  2/13/1962 0:00:00 0900 1962-02-13  
    2  4/13/1972 0:00:00 1000 1972-04-13  
    3  3/13/1982 0:00:00 1101 1982-03-13  
    4 12/13/1992 0:00:00 1603 1992-12-13    


# this doesn't
df$tmp <- strptime(strsplit(as.character(df$date), " ")[[1]][1], format="%m/%d/%Y")
df

    1  2/13/1962 0:00:00 0900 1962-02-13
    2  4/13/1972 0:00:00 1000 1962-02-13
    3  3/13/1982 0:00:00 1101 1962-02-13
    4 12/13/1992 0:00:00 1603 1962-02-13    

I would like to end up with a column that combines the date part of the date and the time column but was unable to get to this result.

While experimenting I noticed that the as.Date function does convert the date . On the other hand, with the strsplit function all rows end up with the first date.

I would greatly appreciate any help towards a solution, ending up with 4 rows have a "Date" object:

    1 1962-02-13 09:00
    2 1972-04-13 10:00
    3 1982-03-13 11:01
    4 1992-12-13 16:03
Thomas
  • 43,637
  • 12
  • 109
  • 140
chribonn
  • 445
  • 5
  • 20
  • How about something like `strptime(paste(df$tmp, df$time), format="%Y-%m-%d %H%M")` (untested, not on my computer atm). Might need `as.character(df$tmp)` in the paste. – r2evans Aug 18 '14 at 14:14
  • @Thomas: Worked! I entered the following: `df$date3 = strptime(paste(as.Date(df$date, format="%m/%d/%Y"), df$time), format="%Y-%m-%d %H%M")` – chribonn Aug 19 '14 at 06:46

1 Answers1

0

You may paste the date and time variable, and then use as.POSIXct with appropriate format:

as.POSIXct(x = paste(as.Date(df$date, format = "%m/%d/%Y"), df$time),
           format = "%Y-%m-%d %H%M")
Henrik
  • 65,555
  • 14
  • 143
  • 159
  • and then format again for the desired style `format(x, format = '%Y-%m-%d %H:%M')` – rawr Aug 18 '14 at 14:27
  • I modified the code as follows: `df$date2 = as.POSIXct(paste(as.Date(df$date, format = "%m/%d/%Y"), df$time), format = "%Y-%m-%d %H%M")`. – chribonn Aug 19 '14 at 06:39