convert_to_date: Convert Numeric and Character Data to Dates

View source: R/utilities.R

convert_to_dateR Documentation

Convert Numeric and Character Data to Dates

Description

This function attempts to convert specified values, vectors, or table columns into date format when possible. The function handles numeric values by treating them as the number of days since a specified origin date, with the default being "1899-12-30" (Excel's origin date). It also attempts to parse character vectors according to common date formats.

Usage

convert_to_date(x, origin = "1899-12-30")

Arguments

x

A numeric or character vector that needs to be converted to the date format.

origin

A character string specifying the origin date for numeric conversions. It must be in "%Y-%m-%d" format.

The default is "1899-12-30".

Details

The function handles different input types:

  • If x is already a Date object, it is returned unchanged.

  • Numeric values are treated as the number of days since origin.

  • Character values are parsed using several common American date formats. If all conversion attempts fail, a warning is issued and the original data is returned.

Value

Returns a vector of class Date. If conversion is not possible for some values, those values will be replaced with NA. If none of the original values can be converted, the original vector will be returned.

Examples

convert_to_date(c("2024-01-01", "February 13, 1999", "2024/02/01", "03/21/2000", "Not date"))
convert_to_date(c(42005, 42006), origin = "1899-12-30")
convert_to_date(c('puppies', 'kittens'))


PHSKC-APDE/rads documentation built on April 14, 2025, 10:47 a.m.