Foxhound
Foxhound

Reputation: 605

Ifelse does not work inside a function

I have come across this issue a couple of times, where placing the ifelse statement inside a function always results in the same result.

Data$QuarterHour <- ifelse( Data$Minute < 15, return( 1 ),
                                  ifelse( Data$Minute < 30 , return( 2 ),
                                          ifelse( DataFrame$Minute < 45, return( 3 ), return( 4 ) ) ) )

This works perfectly fine. However, when I place it into a function. It does not.

calculateHourQuarter <- function( aMinute )
{
ifelse( aMinute < 15, return( 1 ),
        ifelse( aMinute < 30 , return( 2 ),
                ifelse( aMinute < 45, return( 3 ), return( 4 ) ) ) )
}

DataFrame$QuarterHour <- calculateHourQuarter( as.numeric( Data$Minute ) )

This results in the column being filled with 1's. When I call the function interactively in the console, it produces the right result when I just pass it integer's from the console.

Any ideas?

Thanks!

Upvotes: 1

Views: 871

Answers (1)

Zheyuan Li
Zheyuan Li

Reputation: 73405

Remove return statement from your R clause. An R function terminates when it meets a return.

Also, ifelse does not want a return statement, but only returned value. Read ?ifelse again; the first example for ifelse is showing you the correct way to work:

x <- c(6:-4)
sqrt(ifelse(x >= 0, x, NA))

There is no return, right?


Finally, ifelse is really not designed for nesting (although you can). Using cut or findInterval instead (the latter better suits your need here as you want integer result):

findInterval(aMinute, c(0, 15, 30, 45, 60))

Upvotes: 7

Related Questions