rdayofweekweekend

Day of the Week to Return 'weekend' or 'weekday'


I'm brand new to R... I have a column in a data frame where I extracted the days of the week from a date-time column. I would like to add another column to show either "weekend" or "weekday". Where "Sat" and "Sun" return "weekend" and "Mon", "Tue", "Wed", "Thu", "Fri" return "weekday"

day_of_week wkend_wkday
Sat
Mon
Wed
Sun
Fri
Tue
Sat
Wed
Mon

I have tried some ifelse() statements, but it doesn't seem to work.

Thank you!


Solution

  • You can use %in% with ifelse to check whether the day in day_of_week column matches c("Sat", "Sun") vector. If it does,the ifelse function returns weekend. Otherwise, it returns weekday. :

    dat
    
    #  day_of_week
    #1         Sat
    #2         Mon
    #3         Wed
    #4         Sun
    #5         Fri
    #6         Tue
    #7         Sat
    #8         Wed
    #9         Mon
    
    dat$wkend_wkday <- ifelse(dat$day_of_week %in% c("Sat", "Sun"), "weekend", "weekday") 
    
    dat
    #  day_of_week wkend_wkday
    #1         Sat     weekend
    #2         Mon     weekday
    #3         Wed     weekday
    #4         Sun     weekend
    #5         Fri     weekday
    #6         Tue     weekday
    #7         Sat     weekend
    #8         Wed     weekday
    #9         Mon     weekday