警告"条件长度> 1,只使用第一个元素"

Tim*_*Tim 1 r

我的R代码:

bnc1<-function(maxITR=100000, d=2, l=1){
    counts=0;
    for (i in 1:maxITR){
        x=runif(1,0,pi);
        y=runif(2,0,d/2);
        if ((l/2*sin(x)) >= y) counts=counts+1;
    } 
    counts/maxITR*d/l
}
Run Code Online (Sandbox Code Playgroud)

运行代码:

> bnc1(maxITR=1000)
[1] 0.652
There were 50 or more warnings (use warnings() to see the first 50)
> warnings()
Warning messages:
1: In if ((l/2 * sin(x)) >= y) counts = counts + 1 ... :
  the condition has length > 1 and only the first element will be used
2: In if ((l/2 * sin(x)) >= y) counts = counts + 1 ... :
  the condition has length > 1 and only the first element will be used
...
49: In if ((l/2 * sin(x)) >= y) counts = counts + 1 ... :
  the condition has length > 1 and only the first element will be used
50: In if ((l/2 * sin(x)) >= y) counts = counts + 1 ... :
  the condition has length > 1 and only the first element will be used
Run Code Online (Sandbox Code Playgroud)

有谁知道导致警告的原因是什么?

Ale*_*own 6

runif 返回一个向量.

if 采用单个值(不是向量).

检查手册runif,我不认为你正在使用它.


在R中,删除for循环并使用向量通常是有意义的 - 例如:

bnc1<-function(maxITR=100000, d=2, l=1){
    x=runif(maxITR,0,pi);
    y=runif(maxITR,0,d/2);
    counts = sum((l/2*sin(x)) >= y);
    counts/maxITR*d/l
}
Run Code Online (Sandbox Code Playgroud)

  • 每次使用'for'时,请勿使用. (3认同)