Reputation: 340
I'm working on a simple R function as an exercise from a textbook. I have written the function to do the correct action, but I can't understand why mine is throwing a syntax error. I have a solution that works correctly, and both are almost identical so I'm curious as to what is wrong with my code?
This is what the question asks for:
Write a greeting function that says “good morning,” “good afternoon,” or “good evening,” depending on the time of day. (Hint: use a time argument that defaults to lubridate::now()
My code:
salutations = function(now()){
hr = hour(now())
if(4<= hr <= 12){
print("Good Morning")
} else if (13 <= hr <= 19){
print("Good Afternoon")
} else {
print("Good Evening")
}
}
Solution Code:
greet <- function(time = lubridate::now()) {
hr <- lubridate::hour(time)
# I don't know what to do about times after midnight,
# are they evening or morning?
if (hr < 12) {
print("good morning")
} else if (hr < 17) {
print("good afternoon")
} else {
print("good evening")
}
}
Some tings to keep note of: I installed the lubridate
package so even though I am omitting the lubridate::
part I feel it should still work. I have the same amount of braces and tabbing as the solution. So what could be wrong?
Upvotes: 0
Views: 33
Reputation: 541
To start with the you have an extra '}' at the end of your code. Second (4<= hr <= 12) is not a correct syntax. You can write it as:
(hr >= 4 & hr <= 12)
Upvotes: 2
Reputation: 388982
4<= hr <= 12
isn't a valid R syntax.
Probably, what you were trying to do was :
library(lubridate)
hr = hour(now())
if(4 <= hr & hr <= 12){
print("Good Morning")
} else if (13 <= hr & hr <= 19){
print("Good Afternoon")
} else {
print("Good Evening")
}
Upvotes: 1