asmgx
asmgx

Reputation: 7984

Build datetime column in R

I have 2 columns

one is date :

2011-04-13
2013-07-29
2010-11-23

the other is time :

3
22
15

I want to make a new column contains date time

it will be like this

2011-04-13 3:00:00
2013-07-29 22:00:00
2010-11-23 15:00:00

I managed to combine them as string but when i convert them to datetime i get only date the time disappears

any idea how to get date and time in one column?

my script

data <- read.csv("d:\\__r\\hour.csv")
data$date <- as.POSIXct(paste(data$dteday , paste(data$hr, ":00:00", sep=""), sep=" "))

Upvotes: 2

Views: 1325

Answers (2)

asmgx
asmgx

Reputation: 7984

found this fixed the problem

data$date <- as.POSIXct(strptime(paste(data$dteday , paste(data$hr, ":00:00", sep=""), sep=" "), "%Y-%m-%d %H:%M:%S"))

Upvotes: 0

Stephan
Stephan

Reputation: 2236

as example you can use ymd_hm function from lubridate:

a <- c("2014-09-08", "2014-09-08", "2014-09-08")
b <- c(3, 4, 5)

library(lubridate)
library(tidyverse)
tibble(a, b) %>% 
  mutate(time = paste0(a, " ", b, "-0"),
         time = ymd_hm(time))

output would be:

# A tibble: 3 x 3
  a              b time               
  <chr>      <dbl> <dttm>             
1 2014-09-08     3 2014-09-08 03:00:00
2 2014-09-08     4 2014-09-08 04:00:00
3 2014-09-08     5 2014-09-08 05:00:00

Upvotes: 4

Related Questions