So I am trying to separate a column of data ‘DateTime’ to ‘Date’ and ‘Time’ but when I do this it removes the time formatting that contains AM and PM. How can I correctly run this code. Below is what I have been doing in R but I keep on getting errors when I have the format () in the pipe. Please help this newbie
This is one way to do it; using the tidyverse functions:
# load r package libraries
library(tidyverse)
# create sample data
(sample_hr_data <- tibble( #creates a tibble, i.e., a data table; used to build sample data
# as_datetime creates a date time object
var1_date_time = as_datetime(c("2023-11-09 13:40:00", "2023-11-10 04:11:00", "2023-11-12 17:17:00"))
) ) # parenthesis around the entire command will print the result to the console
#> # A tibble: 3 × 1
#> var1_date_time
#> <dttm>
#> 1 2023-11-09 13:40:00
#> 2 2023-11-10 04:11:00
#> 3 2023-11-12 17:17:00
# what it seems that you are asking for help with is this,
# after you have a variable in the date time <dttm> format you can do this
sample_hr_data %>%
# create new variables, one for date and one for time
mutate(
# new variable for date using lubridate::as_date
var2_date = as_date(var1_date_time),
# new variable for time using stringr::str_trunc function
var3_time = str_trunc(
as.character(var1_date_time),
width = 8,
side = "left",
ellipsis = ""
)
)
#> # A tibble: 3 × 3
#> var1_date_time var2_date var3_time
#> <dttm> <date> <chr>
#> 1 2023-11-09 13:40:00 2023-11-09 13:40:00
#> 2 2023-11-10 04:11:00 2023-11-10 04:11:00
#> 3 2023-11-12 17:17:00 2023-11-12 17:17:00