Hi Have 2 columns in a dataframe. Column 1 has Dates like 2017-01-01 and column 2 has time stamp like 1:00 PM.
I need to create another column that combines these 2 information and gives me the 2017-01-01 13:00:00
Hi Have 2 columns in a dataframe. Column 1 has Dates like 2017-01-01 and column 2 has time stamp like 1:00 PM.
I need to create another column that combines these 2 information and gives me the 2017-01-01 13:00:00
Use as.POSIXct
to convert from character to date format.
df$date.time <- as.POSIXct(paste(df$date, df$time), format = "%Y-%m-%d %I:%M %p")
EDIT:
To provide some further context... You paste the date and the time column together to get the string 2017-001-01 1:00 PM
.
You then input the format of the string as a POSIXct argument using format =
. You can see the relationship between symbols and their meaning here.
library(lubridate)
A <- data.frame(X1 = ymd("2017-01-01"),
X2 = "1:00 PM", stringsAsFactors=F)
# X1 X2
# 1 2017-01-01 1:00 PM
library(dplyr)
library(lubridate)
temp <- A %>%
mutate(X3 = ymd_hm(paste(X1, X2)))
X1 X2 X3
<date> <chr> <dttm>
1 2017-01-01 1:00 PM 2017-01-01 13:00:00
B <- data.frame(X1 = ymd("2017-01-01", "2016-01-01"),
X2 = c("1:00 PM", "2:00 AM"), stringsAsFactors=F)
temp <- B %>%
mutate(X3 = ymd_hm(paste(X1, X2)))
# X1 X2 X3
# <date> <chr> <dttm>
# 1 2017-01-01 1:00 PM 2017-01-01 13:00:00
# 2 2016-01-01 2:00 AM 2016-01-01 02:00:00