R apply with a vector parameter

I am trying to apply the ppoibin (poisson binomial probabilities) function from the poibin package to each row in a dataframe. This function takes two parameters: an integer and a vector of probabilities. My data takes the form:

p <- matrix(c(0.046, 0.046, 0.323,
              0.122, 0.122, 0.490,
              0.122, 0.122, 0.490),
            3 , 3, byrow = TRUE)
dat <- data.frame(k = c(0, 1, 0))
dat$p <- p

Within each row, k is the integer where I want to evaluate the probability. The p[,1] p[,2]p[,n] values are the probability parameters for the function.

I can do this row-by-row in a loop and get the correct result:

for (i in c(1:nrow(dat))) {
  dat$prob[i] <- ppoibin(dat$k[i], dat$p[i,])
}

I’d like to avoid the loop. However, if I try to apply the function directly to the dataframe using

dat$prob2 <- ppoibin(dat$k, dat$p[,])

I get an incorrect result. I suspect this requires using apply or more likely mapply, but I’m not sure how.

>Solution :

dat$prob2 <- sapply(1:nrow(dat), function(i) ppoibin(dat$k[i], dat$p[i,]))

Leave a Reply