Is there a way to check if a column is a Date in R?
You could try to coerce all the columns to as.Date
and see which ones succeed. You would need to specify the format you expect dates to be in though. E.g.:
data <- data.frame(
Date=c("10/11/2012","10/12/2012"),
AE=c(1211,100),
Percent=c(0.03,0.43)
)
sapply(data, function(x) !all(is.na(as.Date(as.character(x),format="%d/%m/%Y"))))
#Date AE Percent
#TRUE FALSE FALSE
In R how to calculate if Date is earlier then date X?
You can use pmax
:
DF$Beginning_2 <- pmax(DF$Beginning, as.Date("2020-01-01"))
#DF$Beginning_2 <- pmax(DF$Beginning, "2020-01-01") #Works also
DF
# Beginning End Beginning_2
#1 2020-12-31 2021-01-12 2020-12-31
#2 2018-01-02 2020-03-10 2020-01-01
#3 2019-04-12 2020-12-04 2020-01-01
#4 2020-10-15 2021-03-27 2020-10-15
str(DF)
#'data.frame': 4 obs. of 3 variables:
# $ Beginning : Date, format: "2020-12-31" "2018-01-02" ...
# $ End : Date, format: "2021-01-12" "2020-03-10" ...
# $ Beginning_2: Date, format: "2020-12-31" "2020-01-01" ...
How to validate date in R
Simple way:
d <- try(as.Date(date, format="%d-%m-%Y %H:%M:%S"))
if("try-error" %in% class(d) || is.na(d)) {
print("That wasn't correct!")
}
Explanation: format.Date
uses as.Date
internally to convert date
into an object of the Date
class. However, it does not use a format option, so as.Date
uses the default format, which is %Y-%m-%d
and then %Y/%m/%d
.
The format
option from format.Date
is used only for the output, not for the parsing. Quoting from the as.Date
man page:
The ‘as.Date’ methods accept character strings, factors, logical
‘NA’ and objects of classes ‘"POSIXlt"’ and ‘"POSIXct"’. (The
last is converted to days by ignoring the time after midnight in
the representation of the time in specified timezone, default
UTC.) Also objects of class ‘"date"’ (from package ‘date’) and
‘"dates"’ (from package ‘chron’). Character strings are processed
as far as necessary for the format specified: any trailing
characters are ignored.
However, when you directly call as.Date
with a format specification, nothing else will be allowed than what fits your format.
See also: ?as.Date
R - Date format check
You can use this function:
IsDate <- function(mydate, date.format = "%d/%m/%y") {
tryCatch(!is.na(as.Date(mydate, date.format)),
error = function(err) {FALSE})
}
IsDate(date)
[1] TRUE FALSE FALSE
Original source of the code here.
.
R: Check if a date is valid
Sure. Just try to parse it:
R> days <- 28:31
R> dates <- paste0("2020-02-", days)
R> as.Date(dates)
[1] "2020-02-28" "2020-02-29" NA NA
R>
This shows that in 2020, Feb 28 and 29 existed (leap year) but not 30 and 31.
From you three vectors you could use sprintf("%4d-%02d-%02", y, m, d)
to create a vector of text inputs to parse.
Find date columns in R. Date column have different date-formats. Replace all date format to dd-mmm-yyyy
Using the tidyverse
(see Note):
date_parser <- function(column){
if(any(grepl("[-]",column))){
format(parse_date_time(column,orders = c("dmy","dby","ymd")),"%d-%b-%Y")
}
else column
}
df %>%
mutate_at(-1,~ stringr::str_replace_all(.,"\\/","-")) %>%
purrr::map_dfr(~date_parser(.))
# A tibble: 3 x 5
Name Col2 col3 Col4 col5
<chr> <chr> <chr> <chr> <chr>
1 A 01-Jan-2020 05-Feb-2020 XYZ 01-Mar-2020
2 B 01-Feb-2020 13-Apr-2020 REW 01-Jan-2019
3 C 31-May-2020 17-Sep-2020 RRRR 12-Jan-2020
NOTE:
This is not an actual date, you can convert it again with lubridate
although I doubt dttm
supports mixed dates. Hence as far as I know, you'll still resort to characters.
Related Topics
Shinydashboard Some Font Awesome Icons Not Working
Plot Data Over Background Image with Ggplot
Reshape Multiple Categorical Variables to Binary Response Variables
How to Use Cast or Another Function to Create a Binary Table in R
Getting All Combinations Which Sum Up to 100 Using R
How to Increase the Limit for Max.Print in R
Photo Alignment with Graph in R
Horizontal Dendrogram in R with Labels
Filling in Missing (Blanks) in a Data Table, Per Category - Backwards and Forwards
Convert 12 Hour Character Time to 24 Hour
Add Text on Top of a Faceted Dodged Bar Chart
Calculate Euclidean Distance Matrix Using a Big.Matrix Object
How to Convert Dd/Mm/Yy to Yyyy-Mm-Dd in R
If {...} Else {...}:Does the Line Break Between "}" and "Else" Really Matters