Compare strings with a logical operator in R

I get an error trying to compare and set the values โ€‹โ€‹of the day of the week string as "weekend" or "day of the week" using R. Any suggestions on how best to approach this problem 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 return to RStudio:

 Error in day == "Sat" | "Sun" : operations are possible only for numeric, logical or complex types 
+4
source share
1 answer

Instead of using sapply to cycle through every single day at x and check if it is a day of the week or a weekend, you can do this in one vector 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 is twofold - it will save you from typing, and this will make your code more efficient.

+6
source

All Articles