2
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?

4

1 回答 1

6

您正在寻找mapply

 mapply(assignChance,x,y,chance)

通过sapply在您的代码中使用,您将函数依次assignChance应用于每个元素,并且您将整个向量和. 因此,例如,对于您的第一次迭代,结果调用将是:xbvychancesapply

assignChance(x[1],y,chance)

代替 :

assignChance(x[1],y[1],chance[1])
于 2013-04-18T11:03:36.240 回答