colinfang
colinfang

Reputation: 21707

How to apply a function that take multiple arguments which are both vectors?

chance<-c(0.11,0.12,0.13,0.14,0.15)
aaa<-function(x,y) {
  assignChance <- function (a,b,v) {
    if (a == 0)
      if (b == 0) 1-v
      else v
    else
      if (b == 0) 0
      else 1
  }
  sapply(x,assignChance,y,chance) # this is wrong
}
aaa(c(1,1,0,0,1),c(1,1,1,0,0))

I would expect the outcome as: 1, 1, 0.13, 0.86, 0

Is there any better way for this function. I feel my current attemp is quite ugly as in a functional language I can just use Array.map3 plue pattern match.

Is there a vector version of switch just like ifelse?

Upvotes: 2

Views: 102

Answers (1)

juba
juba

Reputation: 49033

You are looking for mapply :

 mapply(assignChance,x,y,chance)

By using sapply in your code, you are applying the assignChance function to every element of x in turn, and you are passing as b and v arguments your whole vectors y and chance. So, for example, for the first iteration of your sapply, the resulting call will be :

assignChance(x[1],y,chance)

instead of :

assignChance(x[1],y[1],chance[1])

Upvotes: 6

Related Questions