而Loop嵌套在R

时间:2016-12-14 23:38:53

标签: r for-loop while-loop

我有以下问题,我有这个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")

我正在尝试使用以下公式填充Days列:

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

理念是s将是Days,我想用whilePr中的0.3替换MeanProb DataFrame的p值。为了做到这一点,我尝试在for循环中创建一个while循环,但它只填充Days列的第一行:

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
  }
}

但只填充了第一行MeanProb $ Days。我不知道我做错了什么

1 个答案:

答案 0 :(得分: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
  }
}

因为对于每个新行,你想要从0开始,从1开始。我测试它;它有效。