Reputation: 4408
I have a dataframe, df with column DateTimeUTC.
ID DateTimeUTC
A 12/4/2019 11:30:30 PM
A 12/4/2019 11:30:30 PM
B 12/5/2019 11:30:30 PM
B 12/5/2019 11:30:30 PM
B 12/5/2019 11:30:30 PM
I would like to filter, so that DateTimeUTC only displays dates from 12/5/2019, with this outcome:
ID DateTimeUTC
B 12/5/2019 11:30:30 PM
B 12/5/2019 11:30:30 PM
B 12/5/2019 11:30:30 PM
I have tried this command, but have not been successful:
library('dplyr')
library('lubridate')
data %>% filter as.Date(DateTimeUTC == "2019-12-05")
I would like ALL days of 12/5/2019, including the times (hours, min and secs) Is this possible?
Upvotes: 2
Views: 105
Reputation: 887981
Here, the 'DateTimeUTC' is in a different format. Convert the column to DateTime class (it seems that the format is month-day-year-hour-minute-second), and remove the time with as.Date
, then do the comparison (==
)
library(dplyr)
library(lubridate)
data %>%
filter(as.Date(mdy_hms(DateTimeUTC)) == "2019-12-05")
# ID DateTimeUTC
#1 B 12/5/2019 11:30:30 PM
#2 B 12/5/2019 11:30:30 PM
#3 B 12/5/2019 11:30:30 PM
In the OP's code, the as.Date
is applied on a logical vector which would be anyway FALSE
because it is comparing the original format with a different format and this would result in failure of executing the code i.e.
"12/4/2019 11:30:30 PM" == "2019-12-05"
#[1] FALSE
Wrapping as.Date
on this would result in an error
as.Date("12/4/2019 11:30:30 PM" == "2019-12-05")
Error in as.Date.default("12/4/2019 11:30:30 PM" == "2019-12-05") :
do not know how to convert '"12/4/2019 11:30:30 PM" == "2019-12-05"' to class “Date”
data <- structure(list(ID = c("A", "A", "B", "B", "B"),
DateTimeUTC = c("12/4/2019 11:30:30 PM",
"12/4/2019 11:30:30 PM", "12/5/2019 11:30:30 PM", "12/5/2019 11:30:30 PM",
"12/5/2019 11:30:30 PM")), class = "data.frame", row.names = c(NA,
-5L))
Upvotes: 4