Reputation: 548
I have imported a .csv file to a dataframe using the sqldf library, and the .csv starts with 2 seperate fields: "date" and time":
> head(df)
Date Time
1 2021-11-21 10:05:17
2 2021-11-21 10:04:37
3 2021-11-21 10:04:37
4 2021-11-21 10:04:37
5 2021-11-21 09:52:25
> lapply(df,class)
$Date
[1] "character"
$Time
[1] "character"
How do i merge these 2 fields to a new "DateTime" field in the dataframe, so i can sort and filter by date?
What i want to achieve in the end is to be able to query for example like this:
select * where DateTime > '22-01-2022 18:00'
Upvotes: 0
Views: 258
Reputation: 3604
library(lubridate)
as_datetime(paste(df$date, df$time, sep = " "))
so, adding dplyr
library we can:
df |> mutate(newDate = as_datetime(paste(df$date[1], df$time[1], sep = " ")))
#
# A tibble: 2 × 3
date time newDate
<chr> <chr> <dttm>
1 2021-11-21 10:05:17 2021-11-21 10:05:17
2 2021-11-2 10:04:48 2021-11-21 10:05:17
and then you can dplyr::filter(newDate >= as.datetime("2022-01-22 09:00:00))
Grzegorz
Upvotes: 1