1

How would I go about binning these 19 factors together manually?

factor(flights$DEP_TIME_BLK)

19 Levels: 0001-0559 0600-0659 0700-0759 0800-0859 0900-0959 1000-1059 1100-1159 1200-1259 ... 2300-2359

The factor levels each represent different times (e.g. 0001-0559 is nighttime), and I'd like to manually create 4 bins (morning, afternoon, evening, night) corresponding to the various factors (times).

Menno Van Dijk
  • 863
  • 6
  • 24
  • 1
    When asking a question it help if you provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and the desired output for that input. – MrFlick Nov 27 '17 at 16:07

1 Answers1

1
# some data
flights = data.frame(DEP_TIME_BLK = c("0001-0559","0600-0659","1100-
    1159","1200-1259","1300-1359","1900-1959","2300-2359"))

# Choose when dayparts begin; 600 ~ 06:00 etc.
dayparts_start <- c(morning = 600, afternoon = 1300, evening = 1800, night = 
    2300) 

# Here I only use endtime from DEP_TIME_BLK to determine daypart bin
endtime <- as.numeric(gsub("\\d+-", "", flights$DEP_TIME_BLK))

# binning endtimes to daypart bins using cut and then mapping the numeric bins to names
dayparts_bins <- as.numeric(cut(endtime, breaks = c(0,dayparts_start, 2400)))
flights$dayparts_bins_names <- plyr::mapvalues(dayparts_bins, 1:5, 
    c("night", "morning", "afternoon", "evening", "night") )

flights
  DEP_TIME_BLK dayparts_bins_names
1    0001-0559               night
2    0600-0659             morning
3    1100-1159             morning
4    1200-1259             morning
5    1300-1359           afternoon
6    1900-1959             evening
7    2300-2359               night

It's a crude approach, but it might get you started.

Ape
  • 1,159
  • 6
  • 11