简体   繁体   中英

Converting 3 columns (day, month, year) into a single date column R

I have the data-frame called dates which looks like this:

 Day     Month      Year
 2       April      2015
 5       May        2014
 23      December   2017

This code is:

date <- data.frame(Day = c(2,5,23),
                   Month = c("April", "May", "December"),
                   Year = c(2015, 2014, 2017))

I want to create a new column that looks like this:

Day     Month      Year     Date
 2       April      2015    2/4/2015
 5       May        2014    5/5/2014
 23      December   2017    23/12/2017

To do this, I tried:

data <- data %>%
    mutate(Date = as.Date(paste(Day, Month, Year, sep = "/"))) %>% 
    dmy()

But I got an error which says:

Error in charToDate(x) : 
   character string is not in a standard unambiguous format

Is there an obvious error that I'm not seeing?

Thank you so much.

We need to use appropriate format in as.Date . Using base R, we can do

transform(data, Date = as.Date(paste(Day, Month, Year, sep = "/"), "%d/%B/%Y"))

#  Day    Month Year       Date
#1   2    April 2015 2015-04-02
#2   5      May 2014 2014-05-05
#3  23 December 2017 2017-12-23

Or with dplyr and lubridate

library(dplyr)
library(lubridate)

data %>% mutate(Date = dmy(paste(Day, Month, Year, sep = "/")))

You can add format(Date, "%d/%m/%Y") if you need to change the display format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM