Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sapply with custom function (series of if statements)

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!

like image 384
Tom Evans Avatar asked Jan 07 '13 13:01

Tom Evans


2 Answers

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().

like image 179
Stephan Kolassa Avatar answered Sep 20 '22 23:09

Stephan Kolassa


You should be using mapply instead of sapply

mapply(bear.correction,x,y)

[1]  90   0 270 180
like image 45
Gago-Silva Avatar answered Sep 18 '22 23:09

Gago-Silva