简体   繁体   中英

While Loop nested in a for loop in R

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM