Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutate_if or mutate_at in dplyr with Dates

Tags:

r

dplyr

lubridate

I have a data set that is over 100 columns, but for example lets suppose I have a data set that looks like

dput(tib)
structure(list(f_1 = c("A", "O", "AC", "AC", "AC", "O", "A", "AC", "O", "O"), f_2 = c("New", "New", 
"New", "New", "Renewal", "Renewal", "New", "Renewal", "New", 
"New"), first_dt = c("07-MAY-18", "25-JUL-16", "09-JUN-18", "22-APR-19", 
"03-MAR-19", "10-OCT-16", "08-APR-19", "27-FEB-17", "02-MAY-16", 
"26-MAY-15"), second_dt = c(NA, "27-JUN-16", NA, "18-APR-19", 
"27-FEB-19", "06-OCT-16", "04-APR-19", "27-FEB-17", "25-APR-16", 
NA), third_dt = c("04-APR-16", "21-JUL-16", "05-JUN-18", "18-APR-19", 
"27-FEB-19", "06-OCT-16", "04-APR-19", "27-FEB-17", "25-APR-16", 
"19-MAY-15"), fourth_dt = c("05-FEB-15", "25-JAN-16", "05-JUN-18", 
"10-OCT-18", "08-JAN-19", "02-SEP-16", "24-OCT-18", "29-SEP-16", 
"27-JAN-15", "14-MAY-15"), fifth_dt = structure(c(1459728000, 
1469059200, 1528156800, 1555545600, 1551225600, 1475712000, 1554336000, 
1488153600, 1461542400, 1431993600), class = c("POSIXct", "POSIXt"
), tzone = "UTC"), sex = c("M", "M", "F", "F", "M", "F", "F", 
"F", "F", "F")), row.names = c(NA, -10L), class = c("tbl_df", 
"tbl", "data.frame"))

Most of the date (ends_with(dt)) columns are strings, but I want to convert them into dates. I tried mutate_at but received the following:

tib %>% mutate_at(vars(ends_with("dt")), funs(parse_date_time(.))) %>% glimpse()
Error in mutate_impl(.data, dots) : 
  Evaluation error: argument "orders" is missing, with no default.

Any thoughts on what caused this error? Should I use a different mutate function?

like image 445
akash87 Avatar asked May 06 '19 20:05

akash87


1 Answers

As akrun noted, one of the columns is already in dttm format. Once that column is ignored the following code works for me:

tib %>% 
  select(-fifth_dt) %>% 
  mutate_at(vars(ends_with("dt")), parse_date_time, orders = "%d-%m-%y")
like image 60
cardinal40 Avatar answered Nov 12 '22 14:11

cardinal40