R中循环语句的问题

Trouble with a loop statement in R

我在编写正确的 R 代码来执行循环(if else)条件测试时遇到问题。我正在尝试求解 x(必须是整数),使得 F_c = 5(见下文)。 z 和 w 都是一系列已知值,z 代表丰度值,w 代表采样面积。现在我实际上是在输入 x 的随机值,看看我能达到 F_c = 5 有多接近。我想为此编写一个循环,并且当 x 的迭代导致 F_c = 5 时循环停止。任何帮助将不胜感激,我已经在这上面花了很多时间并且还没有发现类似的问题(但如果有的话请告诉我解决方案)。谢谢,

cond = ifelse(z<=x, 1, 0)

F_c = 100*(sum(w*z*cond)/sum(w*z))

不太清楚,但我假设您想知道 w*z 的累计总和达到 sum(w*z) 的百分之五,同时遵循 [=13] 的顺序=].如果这是正确的,你可以试试这个:

 #for every z get the order indices
 indices<-order(z)
 #sort both z and w by z
 z<-z[indices]
 w<-w[indices]
 #now cumsum will give you the cumulative sum of a vector
 #and you compare it  to sum(z*w). 
 #findInterval will give you the index of when you reach .05
 res<-findInterval(.05,cumsum(w*z)/sum(w*z))
 #the value you are looking for:
 z[res]