警告“条件长度> 1且仅使用第一个元素”

时间:2010-12-06 14:06:19

标签: 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
}

运行代码:

> 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

有没有人知道导致警告的原因?

1 个答案:

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