Reputation: 2886
I have code in R which is manipulating timestamps with dyplr The code is below In essence, we send out an email at a certain time and get a response - if any. I wanted to extract a number of attributes from both the sent and response items.
There are 3 countries involved and they have time stamps set up differently So for example UK has a timestamp like: 2015-03-11 09:32:51, where as the other two countries have time stamps like 02/03/2015 08:02
I have created the code below based on my studying of dplyr and i wish to create a function out of it but im getting errors
udf_parsedates <- function(strFormat)
{
Email <- Email %>%
mutate(Email.dtm = parse_date_time(SMS.Date,strFormat),
Email.Hour = as.numeric(format(SMS.dtm,"%H")),
Email.Dow = wday(SMS.dtm, label=TRUE, abbr=FALSE),
Rep.dtm = parse_date_time(Reply.Date,strFormat),
Rep.Hour = as.numeric(format(Rep.dtm,"%H")),
Rep.Dow = wday(Rep.dtm, label=TRUE, abbr=FALSE),
ResponseTime.Hours = as.numeric(difftime(Rep.dtm, SMS.dtm, units="hours")))
}
# Find hour and DOW of the Email
if(Email$dest_ctry == 'GB') {udf_parsedates("%Y-%m-%d %H:%M:%S")
} else if (SMS$dest_ctry == 'IT') {udf_parsedates("%Y/%m/%d %H:%M")
} else if (SMS$dest_ctry == 'ES') {udf_parsedates("%Y/%m/%d %H:%M")}
The mutate works fine outside of the function but im trying to learn to integrate and re-use code so i would like to use functions to do this. Any help would be greatly appreciated
Upvotes: 1
Views: 449
Reputation: 17279
If it were me, I'd try to create a column that shows the date format, and then use and ifelse
to apply to correct transformation into a POSIXct
object
This line in your mutate
call will generate the date format
date_format = ifelse(grepl("\\d{4}-\\d{2}-\\d{2} ", SMS.Date), "ymd", "mdy")
Upvotes: 1