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

时间:2018-07-26 06:02:09

标签: r vectorization mapply

我有一个函数,该函数具有两个要在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?

1 个答案:

答案 0 :(得分:1)

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

选项,例如:

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_)]

足够好了。