Search code examples
rdataframedata-cleaning

Converting dataframe format in R


I have a dataframe which looks as follows :

Type    Availability   Count

DayTime   Cancelled       10
Morning   Cancelled       15
Night     Cancelled       13
DayTime   Trip Completed  14
Morning   Trip Completed  71
Night     Trip Completed  32
DayTime   Not-Present     13
Morning   Not-Present     43
Night     Not-Present     23

I want to convert this data frame into a format which will have only 3 rows, namely, DayTime, Morning and Night. And 3 columns, namely, Cancelled, Trip Completed and Not-Present which will have the respective counts. How can I do that in R ? Please help.


Solution

  • Have a look at tidyr::spread.

    my_data <- tibble::tribble(
      ~Type,    ~Availability,   ~Count,
    
    "DayTime",   "Cancelled",       10,
    "Morning",   "Cancelled",       15,
    "Night",     "Cancelled",       13,
    "DayTime",   "Trip Completed",  14,
    "Morning",   "Trip Completed",  71,
    "Night",     "Trip Completed",  32,
    "DayTime",   "Not-Present",     13,
    "Morning",   "Not-Present",     43,
    "Night",     "Not-Present",     23
    )
    
    my_data %>% tidyr::spread(key = Availability, value = Count)