Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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,]))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading