Tolerance487
Tolerance487

Reputation: 3

How to group data by time in R and count frequency

I want to group the hour to time of the day: i.e., Morning - 00:00:00 - 09:59:59 Afternoon - 10:00:00 - 17:59:59 Evening - 18:00:00 - 23:59:59

This is the input data:

| Date     | Time     |
| 21/10/20 | 03:49:19 |
| 21/10/20 | 05:39:23 |
| 21/10/20 | 09:23:10 |
| 21/10/20 | 14:38:50 |
| 21/10/20 | 17:17:48 |
| 21/10/20 | 21:23:45 |
| 21/10/20 | 21:49:32 |

The output data should be:

| Period    | Count |
| Morning   | 3     |
| Afternoon | 2     |
| Evening   | 2     |

Upvotes: 0

Views: 146

Answers (3)

Ronak Shah
Ronak Shah

Reputation: 388862

Base R :

data$Hour <- as.integer(substr(data$Time, 1, 2))
result <- stack(with(data, table(ifelse(Hour < 10, 'Morning', 
                    ifelse(Hour < 18, 'Afternoon', 'Evening')))))
result

#  values       ind
#1      2 Afternoon
#2      2   Evening
#3      3   Morning

Upvotes: 0

AnilGoyal
AnilGoyal

Reputation: 26218

library(lubridate)
data %>% group_by(period = case_when(hms(Time) < hours(10) ~ 'morning',
                                   hms(Time) < hours(18) ~ 'Afternoon',
                                   TRUE ~ 'Evening')) %>%
  summarise(Count = n())
# A tibble: 3 x 2
  period    Count
  <chr>     <int>
1 Afternoon     2
2 Evening       2
3 morning       3

Upvotes: 0

Waldi
Waldi

Reputation: 41220

You could use hms and case_when:

data <- read.table(text ='
 Date      Time     
"21/10/20" "03:49:19" 
"21/10/20" "05:39:23" 
"21/10/20" "09:23:10" 
"21/10/20" "14:38:50" 
"21/10/20" "17:17:48" 
"21/10/20" "21:23:45" 
"21/10/20" "21:49:32"',header = T)


library(hms)
library(dplyr)

data %>% mutate(period =  case_when(as_hms(Time)<as_hms('10:00:00') ~ 'Morning',
                                    as_hms(Time)<as_hms('18:00:00') ~ 'Afternoon',
                                    T ~ 'Evening')) %>% 
        group_by(Date,period) %>%
        summarize(count=n()) %>%
        ungroup()

#> # A tibble: 3 x 3
#> # Groups:   Date [1]
#>   Date     period    count
#>   <chr>    <chr>     <int>
#> 1 21/10/20 Afternoon     2
#> 2 21/10/20 Evening       2
#> 3 21/10/20 Morning       3

Upvotes: 2

Related Questions