Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare strings with logical operator in R

I'm getting an error trying to compare and set weekday string values as either a "weekend" or a "weekday" using R. Any suggestions on how to approach this problem in a better way would be great.

x <- c("Mon","Tue","Wed","Thu","Fri","Sat","Sun")

setDay <- function(day){
          if(day == "Sat" | "Sun"){
           return("Weekend")
          } else { 
            return("Weekday")
          }
        }

sapply(x, setDay)

This is the error I get back in RStudio:

Error in day == "Sat" | "Sun" : 
  operations are possible only for numeric, logical or complex types
like image 432
Bridgbro Avatar asked Aug 11 '15 17:08

Bridgbro


1 Answers

Instead of using sapply to loop through each individual day in x and check whether it's the weekday or weekend, you can do this in a single vectorized operation with ifelse and %in%:

ifelse(x %in% c("Sat", "Sun"), "Weekend", "Weekday")
# [1] "Weekday" "Weekday" "Weekday" "Weekday" "Weekday" "Weekend" "Weekend"

The motivation for using vectorized operations here is twofold -- it will save you typing and it will make your code more efficient.

like image 59
josliber Avatar answered Sep 23 '22 08:09

josliber