创建一个函数/ forloop,将每个x与所有y进行比较

时间:2020-02-26 21:22:44

标签: r function

我具有此功能,向我显示数字a是否等于或等于数字b,其中1 =是,0 =否:

f <- function(a,b){

  if(((b<0)&(a>= b)&(a<=-b))|((b>0)&(a<= b)&(a>=-b)))
  {
    print(1)
  }
 else
 {
  print(0)
 }

}

最终目标是确定单个数字a的概率比所有b的概率更接近零。

示例:

a  b  prob
1  3   100% (a is equidistant or closer to zero than 5/5 b's)
2  2   60% (a is equidistant or closer to zero than 3/5 b's)
3  1   20% (a is equidistant or closer to zero than 1/5 b's)
4  1    0% (a is equidistant or closer to zero than 0/5 b's)
5  2    0% (a is equidistant or closer to zero than 0/5 b's)

我很难弄清楚如何更改函数或创建forloop,以便它不会逐行计算,而是为每个a,为b的所有值吐出1或0 。之后,我可以轻松地将1加在一起,然后除以观察总数,得出每个a的概率。

任何建议将不胜感激。

1 个答案:

答案 0 :(得分:1)

我认为您想要ifelse,它可以对输入和输出进行向量化

f <- function(a, b) ifelse(((b < 0)&(a >= b)&(a <= -b))|((b > 0)&(a <= b)&(a >= -b)), 1, 0)

f(rnorm(10), rnorm(10))
#> [1] 1 0 0 1 0 0 1 0 0 1

尽管@MauritsEvers指出,但在这里进行逻辑测试本身并强制转换为数字向量是另一种选择:

f <- function(a, b) 1 * (((b < 0) & (a >= b) & (a <= -b)) | ((b > 0) & (a <= b) & (a >= -b)))