I’m making a function that outputs the day of the week, given a number of days since 1/1/1970. The function worked fine when it was a chain of if then statements, but I want to use the function on vectors, so I’ve needed to build this silly looking chain of ifelse statements.
Unfortunately, I keep getting this error:
Error in ifelse(rem == 0, day = "Thursday", ifelse(rem == 1, day = "Friday", :
unused argument(s) (day = "Thursday")
Calls: dayFinder -> ifelse
Execution halted
I haven’t been able to figure out how to get around it – it looks like it’s simply ignoring the then part of the ifelse statement. I’ve tried feeding it a variety of sample data sets or data points and haven’t been able to fix the error.
Here is my code – thanks in advance.
dayFinder <- function(x){
#Assuming that '0' refers to January 1 1970
#Store given number
start <- x
#Initialize variable
day="Halloween"
#Divide x by 7 and store remainder
rem <- x%%7
#Determine the day
ifelse(rem==0, day="Thursday",
ifelse (rem==1, day="Friday",
ifelse (rem==2, day="Saturday",
ifelse (rem==3, day="Sunday",
ifelse (rem==4, day="Monday",
ifelse(rem==5, day="Tuesday",
if (rem==6)
{
day="Wednesday"
}))))))
return(day)
}
q = seq(7,50,1)
z = dayFinder(q)
z
There are a few things wrong with the
ifelsechain, but I’d like to first mention a way to write this kind of selectors in a more readable fashion.Now… about the use of
ifelseand theunused argument error…First off, remember that ifelse() is a function, therefore when you write a statement like
... ifelse(rem == 0, day="Thursday, ..., R will interpret theday="..."part as if you were passing the named argumentdayto the function.Furthermore, in general, you should avoid using
=[most of the time], you probably mean to use<-.Anyway, corrected the ifelse chain should look some’ like