itjcms18 itjcms18 - 2 months ago 14
R Question

applying a function to a timeseries in a R dataframe

I'm trying to apply a function to a column in a dataframe that contains dates and keep getting an error. I'm not exactly sure what I'm doing wrong.

My dataframe:

dates total
1 2014-12-08 01:10:00 163.7
2 2014-12-08 01:10:00 163.9
3 2014-12-08 01:12:00 163.6
4 2014-12-08 08:27:00 163.0
5 2014-12-08 08:35:00 163.7
6 2014-12-08 08:39:00 162.4


I want to replace the dates by either 'morning' or 'night' or alternatively created a new column with 'morning' or 'night'. the approach that i took involved unclassing the date so i could get the hour. I defined a night as before 4am or after 5pm. I put this in a function called timeofday:

timeofday <- function(x) {
bmk <- unclass(x)
if (bmk$hour < 4) {
return("night")
} else if (bmk$hour > 17) {
return("night")
} else {
return("morning")
}
}


I then did the following:

timeofday(df$dates)

Warning message:
In if (bmk$hour < 4) { :
the condition has length > 1 and only the first element will be used


Any help on identifying the issue would be greatly appreciated.

Answer

you could also use cut as in:

cut(unclass(x)$hour-7,c(0,15,24)-8,c('night','morning'))

(note that you have to shift your frame of reference so that you don't have two 'night' categories with this solution)