itjcms18 itjcms18 - 1 year ago 64
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) {
} else if (bmk$hour > 17) {
} else {

I then did the following:


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 Source

you could also use cut as in:


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download