将函数(分布)传递给其他函数本身的参数

时间:2022-06-26 16:04:27

I am trying to do multiple samples of a distribution with a function. The trouble I am having is that when I pass the distribution into the function all the means come out the same as it appears my distribution is not being run each time inside the for loop. Test line:

我试图用函数做一个分布的多个样本。我遇到的麻烦是,当我将分布传递给函数时,所有的方法都出现了相同的情况,因为每次在for循环中都没有运行我的分布。测试线:

test(100,100,dist = rbinom(x, 1, 0.50))

Code

test = function(N, n, dist){
  means = matrix(rep(0,times=N,nrow=N,ncol=1))
  x = n
  for(i in 1:N){
    means[i,1]<- mean(dist)
    print(means[i,1])
  }
}

This question is similar to Passing a function argument to other arguments which are functions themselves but I seem to be having a different type of problem.

这个问题类似于将函数参数传递给其他函数本身的参数,但我似乎遇到了不同类型的问题。

1 个解决方案

#1


0  

One option would be to pass function and parameters separately. E.g.

一种选择是分别传递函数和参数。例如。

test(100, 100, dist = rbinom, list(1, 0.5))

test = function(N, n, dist, ...){
  means = matrix(rep(0,times=N,nrow=N,ncol=1))
  x = n
  for(i in 1:N){
    means[i, 1] <- mean(do.call(dist, c(x, ...)))
    print(means[i, 1])
  }
}

#1


0  

One option would be to pass function and parameters separately. E.g.

一种选择是分别传递函数和参数。例如。

test(100, 100, dist = rbinom, list(1, 0.5))

test = function(N, n, dist, ...){
  means = matrix(rep(0,times=N,nrow=N,ncol=1))
  x = n
  for(i in 1:N){
    means[i, 1] <- mean(do.call(dist, c(x, ...)))
    print(means[i, 1])
  }
}