使用自定义函数对 data.table 中的子集使用 mapply

Using mapply on a subset in a data.table with a custom function

我有一个包含两个变量的函数,我想在 data.frame 上 运行,但只针对一个子集。要 运行 我使用 mapply 的功能。但是我得到的子集行的结果是排除行的结果?也许你能帮忙?谢谢

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?

我认为在 OP 想要实现的范围内不需要 mapply

选项如:

library(data.table)
test[Distri == "PV", R := find_s_loss_poisson(DDLT,ExpBO)]

test[, R := ifelse(Distri == "PV", find_s_loss_poisson(DDLT,ExpBO), NA_integer_)]

就够了。