sapply with custom function (series of if statements)

Tom Evans picture Tom Evans · Jan 7, 2013 · Viewed 10.6k times · Source

I want to run a function which looks at two vectors, returning different values depending on the signs of the values in the two vectors. I have written a function which works to compare two values, but then I want to run this on two vectors. So I used sapply, but I am getting different results than expected.

bear.correction<-  function(x,y){
                                if(x > 0 && y < 0){
                                  return(90)
                                }else if(x < 0 && y < 0){
                                  return(180)
                                }else  if(x < 0 && y > 0){
                                  return(270)
                                }else   return(0)
                              }

The following give the expected (and desired) result:

  bear.correction(1,-1)
  bear.correction(1,1)
  bear.correction(-1,1)
  bear.correction(-1,-1)

Result: 90, 0, 270, 180

However when I try to do the same comparisons, but using vectors with sapply I get a different result:

  x <- c(1,1,-1,-1)
  y <- c(-1,1,1,-1)
  sapply(x,bear.correction,y)

Result: 90, 90, 180, 180.

I can't see what's wrong, so please help!

Answer

Stephan Kolassa picture Stephan Kolassa · Jan 7, 2013

You should be using mapply() instead of sapply():

mapply(bear.correction,x,y)

Why? Your sapply() applies bear.correction() to each entry of x... but giving it the entire y vector as a second argument in each case, and so bear.correction() only looks at the first entry in y in all four cases. To "walk along" multiple entries in multiple vectors (or other data structures), use mapply().