英文:
R generate random data from several distributions using kwargs
问题
问题:
我想从多个分布中生成随机样本,例如norm
、pois
等。然而,我想要指定给rdist
函数的参数,就像传递参数给函数调用一样。
尝试:
我尝试了一些我在Python中做的事情,例如partial
或**kwargs
dist = 'rnorm' # 分布
n = 100 # 样本大小
para1 = c(0,1) # 参数
mean(get(dist)(n,para1)) # 失败
para2 = c(mean = 0, sd = 1) # 参数
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
dist = 'rnorm' # dist
n = 100 # sample size
para1 = c(0,1) # parameters
mean(get(dist)(n,para1)) # it fails
para2 = c(mean = 0, sd = 1)# parameters
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
):
## 从标准正态分布中抽样
(X <- do.call("rnorm", args = list(n = 10, mean = 0, sd = 1)))
#> [1] 1.4127136 -0.4113396 1.7546034 0.6741983 -1.3499156 -0.8033819
#> [7] -1.6393473 -0.7667389 0.7157213 -1.1061452
mean(X)
#> [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
):
## sample from standard normal
(X <- do.call("rnorm", args = list(n = 10, mean = 0, sd = 1)))
#> [1] 1.4127136 -0.4113396 1.7546034 0.6741983 -1.3499156 -0.8033819
#> [7] -1.6393473 -0.7667389 0.7157213 -1.1061452
mean(X)
#> [1] -0.1519632
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论