0

I have the following problem, I have this data.frame

MeanProb <-structure(list(spp = structure(c(1L, 2L, 4L, 3L, 5L, 6L, 7L, 
9L, 8L, 10L, 11L, 13L, 14L, 15L, 12L), .Label = c("ANPA", "EPFU", 
"EUMA", "EUPE", "LABL", "LACI", "LANO", "MYCA", "MYCI", "MYEV", 
"MYLU", "MYTH", "MYYU", "PAHE", "TABR"), class = "factor"), PSI = c(0.11, 
0.09, 1, 1, 0.28, 0.6, 0.49, 0.1, 0.82, 0.76, 0.73, 0, 0, 0.66, 
0.18), P = c(0.310400865105502, 0.407499355437779, 0.0260179560958289, 
0.00618257990834879, 0.201530599145313, 0.442993326882614, 0.653241682633141, 
0.392164812646201, 0.738867446144311, 0.644245184328625, 0.732752266966217, 
0.144457717963026, 0.028099503540885, 0.654181508254556, 0.299160511936956
), Days = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
NA, NA)), .Names = c("spp", "PSI", "P", "Days"), row.names = c(NA, 
-15L), class = "data.frame")

I am trying to populate the Days column using the following formula:

s = 1
a = 0
while (a < 0.95) {
    a <- (1-(1-0.3)^s)
    s = s+1
}
print(s)

The Idea is that s is going to be Days, and I want to replace the 0.3 in the while loop with the values of the p Value of the MeanProb DataFrame. In order to do that I tried to make a while loop within the for loop, but it only populates the first row of the Days column:

s = 1
a = 0
for (i in 1:NROW(MeanProb)){
while (a < 0.95) {
  a <- (1-(1-MeanProb$P[i])^s)
  s = s+1
  MeanProb$Days[i] <- s
  }
}

But only the first row of MeanProb$Days is populated. I don't know What I am doing wrong

1
  • If you know another language to try it in, check out: pythontutor.com/visualize.html#mode=edit | maybe you need to reset a variable to the starting value after each time you do the while loop? Commented Dec 14, 2016 at 23:40

1 Answer 1

4
for (i in 1:NROW(MeanProb)){
s = 1
a = 0
while (a < 0.95) {
  a <- (1-(1-MeanProb$P[i])^s)
  s = s+1
  MeanProb$Days[i] <- s
  }
}

since for each new row, you want to start a from 0 and s from 1. i've test it; it works.

Sign up to request clarification or add additional context in comments.

1 Comment

It is also ceiling(log(0.05)/log(1 - MeanProb$P)) + 1 without using loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.