生成随机数据来自多个分布,使用kwargs参数。

huangapple go评论94阅读模式
英文:

R generate random data from several distributions using kwargs

问题

问题:

我想从多个分布中生成随机样本,例如normpois等。然而,我想要指定给rdist函数的参数,就像传递参数给函数调用一样。

尝试:

我尝试了一些我在Python中做的事情,例如partial**kwargs

  1. dist = 'rnorm' # 分布
  2. n = 100 # 样本大小
  3. para1 = c(0,1) # 参数
  4. mean(get(dist)(n,para1)) # 失败
  5. para2 = c(mean = 0, sd = 1) # 参数
  6. mean(get(dist)(n,para2)) # 失败

输出:
> ```R
[1] 0.6318898
[2] 0.4246129

从输出中可以看出,rnorm没有生成来自norm(mean = 0,sd = 1)的样本,因为样本均值约为0.5。输出的随机数是分别从rnorm(1,mean = 0,sd = 1)rnorm(1,mean = 1, sd =1)生成的。

英文:

Question:

I want to generate random sample from several distributions, e.g. norm, pois etc. However, I want to specify parameters to rdist function, like passing parameters to function call.

Attempt:

I tried with something I did in python partial or **kwargs

  1. dist = 'rnorm' # dist
  2. n = 100 # sample size
  3. para1 = c(0,1) # parameters
  4. mean(get(dist)(n,para1)) # it fails
  5. para2 = c(mean = 0, sd = 1)# parameters
  6. mean(get(dist)(n,para2)) # it fails

Output:
> ```
[1] 0.6318898
[2] 0.4246129

As we can see from the output, rnorm did not produce samples from norm(mean = 0,sd = 1),beacause sample mean is around 0.5. The output randoms are generated from rnorm(1,mean = 0,sd = 1) and rnorm(1,mean = 1, sd =1) one by one.

答案1

得分: 1

你可以使用 do.call 来调用一个函数作为字符名称,并将函数参数传递在一个列表中(还可参考 ?do.call):

  1. ## 从标准正态分布中抽样
  2. (X <- do.call("rnorm", args = list(n = 10, mean = 0, sd = 1)))
  3. #> [1] 1.4127136 -0.4113396 1.7546034 0.6741983 -1.3499156 -0.8033819
  4. #> [7] -1.6393473 -0.7667389 0.7157213 -1.1061452
  5. mean(X)
  6. #> [1] -0.1519632
英文:

You can use do.call to call a function as a character name and pass function arguments in a list (see also ?do.call):

  1. ## sample from standard normal
  2. (X &lt;- do.call(&quot;rnorm&quot;, args = list(n = 10, mean = 0, sd = 1)))
  3. #&gt; [1] 1.4127136 -0.4113396 1.7546034 0.6741983 -1.3499156 -0.8033819
  4. #&gt; [7] -1.6393473 -0.7667389 0.7157213 -1.1061452
  5. mean(X)
  6. #&gt; [1] -0.1519632

huangapple
  • 本文由 发表于 2020年1月6日 15:12:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/59608029.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定