Notice message by adding year, month and day with the ymd() function of the lubridate

Asked

Viewed 42 times

3

I’m practicing with the pack hflights

I install the package;

I load the package; and

I carry the lubridate

install.packages("hflights")
library(hflights)
library(lubridate)

The data (Year, Month, DayofMonth) come separate and would like to join them.

To this end, I combined the function ymd() of lubridate along with the function paste0 of base, as follows:

hflights %>% 
  mutate(dt=ymd(paste0(Year, "0", Month, DayofMonth))) %>% 
  select(dt) %>% 
  head()

Apparently, it worked:

   dt
1 2011-01-01
2 2011-01-02
3 2011-01-03
4 2011-01-04
5 2011-01-05
6 2011-01-06
Warning message:
 39539 failed to parse. 

It turns out that the result came accompanied by the message

Warning message:
 39539 failed to parse.

I know this doesn’t mean a mistake, but a warning message. I just couldn’t identify what that warning means. The R failed to analyze what, more precisely?

1 answer

6


Just change the paste0 for paste with the argument sep = "-".

library(hflights)
library(dplyr)
library(lubridate)

hflights %>% 
  mutate(dt = ymd(paste(Year, Month, DayofMonth, sep = "-"))) %>% 
  select(dt) %>% 
  head()
#          dt
#1 2011-01-01
#2 2011-01-02
#3 2011-01-03
#4 2011-01-04
#5 2011-01-05
#6 2011-01-06

Although the package lubridate be very useful, in this case no need to load it, the base function as.Date enough to solve the problem.

library(hflights)
library(dplyr)

hflights %>% 
  mutate(dt = as.Date(paste(Year, Month, DayofMonth, sep = "-"))) %>% 
  select(dt) %>% 
  head()
#          dt
#1 2011-01-01
#2 2011-01-02
#3 2011-01-03
#4 2011-01-04
#5 2011-01-05
#6 2011-01-06

Browser other questions tagged

You are not signed in. Login or sign up in order to post.