HNSKD HNSKD - 1 month ago 20
R Question

How to coerce date type for variables in dataframe using dplyr and a helper function in r?

I have a dataframe consisting of 50 variables. For simplicity, I have created a dataframe of 5 variables. I want the variables in position 2:5 to be coerced as date variables instead of character variables.

ID<-1:3
ASSISTANCEPERIODFROM<-c("14/06/2009", "13/01/2010","13/01/2010")
ASSISTANCEPERIODTO<-c("14/06/2009","30/06/2010","30/06/2010")
APPROVEDDATE<-c("14/11/2009","30/12/2010","30/01/2011")
DATEOFBIRTH<-c("14/11/1990","30/12/1970","30/01/2000")

df<-data.frame(ID,ASSISTANCEPERIODFROM,ASSISTANCEPERIODTO,APPROVEDDATE,DATEOFBIRTH,stringsAsFactors=FALSE)


I tried the
mutate_each
function in dplyr, along with the helper function,
contains
, but when I tried for two strings, I could not get the results I want. The two strings are
PERIOD
and
DATE
. Below are my method.

library(dplyr)
library(stringr)
library(lubridate)

df<-df %>%
mutate_each(funs(dmy(.)),contains(c("PERIOD","DATE")))
# Error: is.string(match) is not TRUE

df<-df %>%
mutate_each(funs(dmy(.)),contains("PERIOD"|"DATE"))
# Error in "PERIOD" | "DATE" :
# operations are possible only for numeric, logical or complex types

df<-df %>%
mutate_each(funs(dmy(.)),contains("PERIOD|DATE"))
# No error but doesn not give me what I want

df<-df %>%
mutate_each(funs(dmy(.)),as.numeric(str_detect(colnames(df),"PERIOD|DATE")))


I also tried my luck at
str_detect
but it would not work either.

Answer

contains doesn't deal with regex, so it doesn't detect any column containing PERIOD|DATE. Try:

df %>% mutate_each(funs(dmy(.)),union(contains("PERIOD"),contains("DATE")))
#  ID ASSISTANCEPERIODFROM ASSISTANCEPERIODTO APPROVEDDATE DATEOFBIRTH
#1  1           2009-06-14         2009-06-14   2009-11-14  1990-11-14
#2  2           2010-01-13         2010-06-30   2010-12-30  1970-12-30
#3  3           2010-01-13         2010-06-30   2011-01-30  2000-01-30

Otherwise, just use matches:

df %>% mutate_each(funs(dmy(.)),matches("PERIOD|DATE"))

to get the same result.

Comments