[R] ifelse question (I'm not sure why this is working)...

Jim Lemon jim at bitwrit.com.au
Tue Sep 10 23:39:01 CEST 2013


On 09/11/2013 05:40 AM, Jonathan Greenberg wrote:
> R-helpers:
>
> One of my intrepid students came up with a solution to a problem where
> they need to write a function that takes a vector x and a "scalar" d,
> and return the indices of the vector x where x %% d is equal to 0 (x
> is evenly divisible by d).  I thought I had a good handle on the
> potential solutions, but one of my students sent me a function that
> WORKS, but for the life of me I can't figure out WHY.  Here is the
> solution:
>
> remainderFunction<-function(x,d)
> {
>     ifelse(x%%d==0,yes=return(which(x%%d==0)),no=return(NULL))
> }
> remainderFunction(x=c(23:47),d=3)
>
> I've never seen an ifelse statement used that way, and I was fully
> expecting that to NOT work, or to place the output of which(x%%d==0)
> in each location where the statement x%%d==0 was true.
>
> Any ideas on deconstructing this?
>
> --j
>
Hi Jonathan,
While this has already been answered, the question was "why does it 
work?". As Bill Dunlap pointed out, it is because the "return" does not 
allow the ifelse to complete. That was not a problem for the student, 
for it did do what was requested. It is just an unnecessary elaboration 
of the code, for:

remainderFunction<-function(x,d) {
  which(x%%d==0)
}

works just as well. I think Bill was pointing out the the order of 
evaluation was important, for:

remainderFunction<-function(x,d) {
  which(return(x%%d==0))
}

doesn't work. The student probably deserves a Rube Goldberg award.

Jim



More information about the R-help mailing list