Reputation: 465
I have a function with two variables I want to run on a data.frame, but just for a subset. To run the function I use mapply. But the result I get for the subsetted row is the result for excluded row? Maybe you can help? Thanks.
find_s_loss_poisson <- Vectorize(function(lam, target){
precision <- 5
if(target > lam){
return(0)
}else{
target <- round(target, precision)
loss <- lam
i = 0
while (round(loss, precision) > target){
i <- i + 1
loss <- loss - (1 - ppois(i - 1, lam, 1))
}
return(i)
}
})
test <- data.table(W = c(50, 51),
P = c("A", "B"),
Distri = c("NV", "PV"),
DDLT = c(409, 0.080),
Sigma = c(194, 0.284605),
ExpBO = c(0.2071, 0.104),
z = c(0.48, 9999))
test[Distri == "PV", R := mapply(function(x,y) find_s_loss_poisson(x,y), test$DDLT, test$ExpBO)]
test
find_s_loss_poisson(0.08, 0.1040) # result is 0 and this should be the value in R
find_s_loss_poisson(409, 0.2071) # the result of the 1st line is 449 and this is now in R for the 2nd line?
Upvotes: 1
Views: 206
Reputation: 20085
I dont think mapply
is needed in scope of what OP wants to achieve.
Options like:
library(data.table)
test[Distri == "PV", R := find_s_loss_poisson(DDLT,ExpBO)]
OR
test[, R := ifelse(Distri == "PV", find_s_loss_poisson(DDLT,ExpBO), NA_integer_)]
will be good enough.
Upvotes: 2