r - 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) # wrong } aaa(c(1,1,0,0,1),c(1,1,1,0,0))
i expect outcome as: 1, 1, 0.13, 0.86, 0
is there better way function. feel current attemp quite ugly in functional language can use array.map3
plue pattern match
.
is there vector version of switch
ifelse
?
you looking mapply
:
mapply(assignchance,x,y,chance)
by using sapply
in code, applying assignchance
function every element of x
in turn, , passing b
, v
arguments whole vectors y
, chance
. so, example, first iteration of sapply
, resulting call :
assignchance(x[1],y,chance)
instead of :
assignchance(x[1],y[1],chance[1])
Comments
Post a Comment