Scanner
Scanner

Reputation: 73

How to convert a partial date for a dataframe in R into a date column?

So assuming I have a df like:

   <chr>          <chr>            <chr>
  Category        Date             Type
1 x               Jan 2              g
2 x2              Jan 5              a
3 x3              Mar 7              b
4 x4              Apr 9              c 
5 x5              Dec 12             o

How would I use the lubridate library to convert my character dates into actual dates?

I've been trying to use lubridate but not sure how to convert the chars into number e.g. Jan into 1, Mar into 3 or directly convert them given that they aren't in the mdy() function scope as they are partial dates.

Upvotes: 0

Views: 423

Answers (2)

akrun
akrun

Reputation: 887501

We can use

library(lubridate)
mdy(x, truncated = 2)
#[1] "2020-01-02"

data

x <- "Jan 2"

Upvotes: 1

user12635841
user12635841

Reputation:

Just provide a year:

x <- c("Jan 2")
as.Date(paste0("2020 ", x), "%Y %b %d")
# "2020-01-02"

Upvotes: 2

Related Questions