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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With