8

I have the following dataframe

 Date             Time
10/03/2014       12.00.00
11/03/2014       13.00.00
12/03/2014       14.00.00

I want to create one single column as follows

DT
10/03/2014 12.00.00
11/03/2014 13.00.00
12/03/2014 14.00.00

when I run

data$DT <- as.POSIXct(paste(x$Date, x$Time), format="%d-%m-%Y %H:%M:%S")

I get a column DT with all NA values.

A. Suliman
  • 12,923
  • 5
  • 24
  • 37
Nikhil Mangire
  • 397
  • 5
  • 13

3 Answers3

6
Data$DT <- as.POSIXct(as.character(paste(data$Date, data$Time)), format="%d/%m/%Y %H.%M.%S")

OR

data$Time <- gsub('\\.',':',data$Time)
data$Date <- gsub('/','-',data$Date)

data$DT <- as.POSIXct(as.character(paste(data$Date, data$Time)), format="%d-%m-%Y %H:%M:%S")
A. Suliman
  • 12,923
  • 5
  • 24
  • 37
2

Use the package lubridate:

data$DT <- with(data, ymd(Date) + hms(Time))

If you want the column to be a POSIXct, do the following after that:

data$DT <- as.POSIXct(data$DT)
morgan121
  • 2,213
  • 1
  • 15
  • 33
2

This should be a very common problem, hence contributing with a reproducible answer using dplyr:

## reproducible example
library(dplyr)
library(magrittr)
DF <- data.frame(Date = c("10/03/2014", "11/03/2014", "12/03/2014"),
                 Time = c("12.00.00", "13.00.00", "14.00.00"))

DF_DT <- DF %>% 
  mutate(DateTime = paste(Date, Time)) %>% 
  mutate(across('DateTime', ~ as.POSIXct(.x, format = "%d/%m/%Y %H.%M.%S")))
vlad1490
  • 355
  • 2
  • 8