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

问题描述 投票:2回答:1

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

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

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])
  }
}

这个问题与Passing a function argument to other arguments which are functions themselves类似,但我似乎遇到了不同类型的问题。

r
1个回答
0
投票

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

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])
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.