John Perez
John Perez

Reputation: 117

R- Create a new field applying condition on a Date field

I am new in R. I am working with windows 10. I have R Studio and R version 3.5.0.

I have a table with one field dateTime format.

2012-02-02 10:04:00
2012-08-13 11:38:00
2012-07-13 14:00:00
2012-09-26 08:45:00
2012-10-24 05:39:00
2012-02-03 03:33:00
2012-05-02 06:30:00
2012-06-27 09:00:00
2012-07-09 10:16:00
2012-11-22 13:13:00

I need to create a new field that splits the data between summer and winter: From May to September would be Summer and from October to April would be Winter. Based on the result of this new field, create another one that separates the data between times of the day: morning, noon, afternoon and night for summer and the same for winter. The conditions would be:

For Summer
     *  Morning Summer: 5 am – 10 am 
     *  Noon Summer: 10 am -12 pm 
     *  Afternoon Summer: 12 pm -8 pm 
     *  Night summer 8 pm – 5 am 
For Winter
     *  Morning Winter: 7 am – 11 am 
     *  Noon Winter: 11 am -12 pm 
     *  Afternoon Winter: 12 pm -4 pm 
     *  Night Winter 4 pm – 7 am

the result would be something like this:

 date                 | season |    time Of Day
'2012-02-02 10:04:00' | winter | morning
'2012-08-13 11:38:00' | summer | noon
'2012-07-13 14:00:00' | summer | afternoon
'2012-09-26 08:45:00' | summer | morning
'2012-10-24 05:39:00' | winter | night
'2012-02-03 03:33:00' | winter | night
'2012-05-02 06:30:00' | summer | morning
'2012-12-27 09:00:00' | winter | morning
'2012-07-09 10:16:00' | summer | morning
'2012-11-22 13:13:00' | winter | afternoon 

For the first case, (split between summer and winter) I tried to use case_when, but it did not work:

df %>% 
  mutate(season = case_when(
    month(.$date) > 4 & month(.$date)< 10 ~ "summer",
    month(.$date) < 5 & month(.$date) > 10 ~ "winter"
    ))
Error in mutate_impl(.data, dots) : 
  Evaluation error: do not know how to convert 'x' to class 
<U+0093>POSIXlt<U+0094>.

I tried to find something about the error, but to be honest I did not get how to solve the problem. I tried to use library "lubridate" but still doesn't work.

Any idea of how to do it?

Upvotes: 0

Views: 2345

Answers (1)

A. Suliman
A. Suliman

Reputation: 13125

 df %>% mutate_if(is.character, as.POSIXct) %>% 
          mutate(season = case_when(
                          month(date) > 4 & month(date) < 10 ~ "summer",
                          month(date) < 5 & month(date) > 10 ~ "winter"
        ))

Data

 data <- read.table(text="
                       date
               '2012-02-02 10:04:00'

               '2012-08-13 11:38:00'

               '2012-07-13 14:00:00'

               '2012-09-26 08:45:00'

              ",header=T, stringsAsFactors = F)

Upvotes: 2

Related Questions