I have two objects named "Date" and "Time". The date is in YYYY.mm.dd and time is in HH:MM format. I need to create a date and time object for my financial econometrics assignment.
First I paste two objects together and create a character vector such like following:
Date Time Open High Low
1 2017.09.01 00:00 1.19013 1.19017 1.19013
2 2017.09.01 00:01 1.19015 1.19017 1.19015
DATA<-DAT%>%select(Date,Time,Open,High,Low)%>%
mutate(Date_Time=as.POSIXct(paste(DATA$Date, DATA$Time), format="%YYYY.%mm.%dd %H:%M"))
> head(DATA$Date_Time)
[1] NA NA NA NA NA NA
You can also use the lubridate
package (part of the Tidyverse) that has functions to convert strings to date or date-time objects using the functions like ymd_hm()
.
library(tidyverse)
library(lubridate)
df <- tribble(~Date, ~Time, ~Open, ~High, ~Low,
"2017.09.01", "00:00", "1.19013", "1.19017", "1.19013",
"2017.09.01", "00:01", "1.19015", "1.19017", "1.19015")
df %>% mutate(Date.Time = ymd_hm(paste(Date, Time, sep=" ")))
which produces
# A tibble: 2 x 6
Date Time Open High Low Date.Time
<chr> <chr> <chr> <chr> <chr> <dttm>
1 2017.09.01 00:00 1.19013 1.19017 1.19013 2017-09-01 00:00:00
2 2017.09.01 00:01 1.19015 1.19017 1.19015 2017-09-01 00:01:00