0
votes

I used the following R code to create a POSIXct date time field from a separate date and time field both in character format using lubridate and dplyr.

library(dplyr)
library(lubridate)
c_cycle_work <- tibble(
  StartDate = c("1/28/2011", "2/26/2011", "4/2/2011", "4/11/2011"),
  StartTime = c("10:58", "6:02", "6:00", "9:47")
)

c_cycle_work %>%
  mutate(start_dt = paste0(StartDate, StartTime, sep = " ", collapse = NULL)) %>%
  mutate(start_dt = mdy_hms(start_dt))

# 1 1/28/2011     10:58   2020-01-28 11:10:58
# 2 2/26/2011      6:02   2020-02-26 11:06:02
# 3  4/2/2011      6:00   2020-04-02 11:06:00
# 4 4/11/2011      9:47   2020-04-11 11:09:47

The start_dt field I created is in Y m d format even though I used mdy_hms based on the data. Also, all years have been changed to 2020.

Went over this several times, used paste vs. paste0, etc. but still stumped.

1
Dates and the date part of datetimes are always printed in their ISO format in R. The reader function is for the input format, not output.alistaire
Is there any relation between changing integers to strings and the question? Shouldn't you edit the title?Rui Barradas
I was searching for something related to that earlier. How do I change the title?smp201804
Title edited. I copied and pasted from your comment to the answer by @MrFlick.Rui Barradas

1 Answers

1
votes

Your problem is the paste0() which doesn't have a sep= argument. So when you paste the date and time you get 1/28/201110:58 and it spilts that into 1/28/20/11/10/58 though it seemed to work differently with my version lubridate_1.6.0. Also you where use "hms" but your times didn't have seconds. This should work with your data

c_cycle_work %>%
  mutate(start_dt = paste(StartDate,  StartTime, sep=" ")) %>% 
  mutate(start_dt = mdy_hm(start_dt))

#   StartDate StartTime            start_dt
#       <chr>     <chr>              <dttm>
# 1 1/28/2011     10:58 2011-01-28 10:58:00
# 2 2/26/2011      6:02 2011-02-26 06:02:00
# 3  4/2/2011      6:00 2011-04-02 06:00:00
# 4 4/11/2011      9:47 2011-04-11 09:47:00