函数将从形状参数为alpha且速率参数为beta的伽玛分布中生成大小为n的迭代样本 [英] Function that will generate iter samples of size n from a gamma distribution with shape parameter alpha and rate parameter beta

查看:126
本文介绍了函数将从形状参数为alpha且速率参数为beta的伽玛分布中生成大小为n的迭代样本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该函数需要返回每个样本的平均值和标准偏差.

The function needs to return the mean and standard deviation of each sample.

这就是我所拥有的:

sample_gamma <- function(alpha, beta, n, iter) {
  mean = alpha/beta
  var = alpha/(beta)^2
  sd = sqrt(var)
  gamma = rgamma(n,shape = alpha, scale = 1/beta)
  sample_gamma = data.frame(mean = replicate(n = iter, expr = mean))
}

我为此非常迷失.我还需要为此功能创建一个数据框.

I'm very lost for this. I also need to create a data frame for this function.

谢谢您的时间.

sample_gamma <- function(alpha, beta, n, iter) {
  output <- rgamma(iter, alpha, 1/beta)
  output_1 <- matrix(output, ncol = iter)
  means <- apply(output_1, 2, mean)
  sds <- apply(output_1, 2, sd)
mystats <- data.frame(means, sds)
return(mystats)
  }

除sds以外,此方法均有效.它正在返回NA.

This works except for the sds. It's returning NAs.

推荐答案

我不清楚您想要什么.但是假设您要创建10个大小为1000,alpha = 1,beta = 2的样本.那么您可以创建一个rgamma实现流,将它们标注为矩阵,然后使用apply获取统计信息,最后创建一个数据框带有这些向量:

It's not really clear to me what you want. But say you want to create 10 samples of size 1000, alpha = 1, beta = 2. Then you can create a single stream of rgamma realizations, dimension them into a matrix, then get your stats with apply, and finally create a data frame with those vectors:

output <- rgamma(10*1000, 1, 1/2)
output <- matrix(output, ncol = 10)
means <- apply(output, 2, mean)
sds <- apply(output, 2, sd)
mystats <- data.frame(means, sds)

您可以将函数包装在该代码周围,用参数替换硬值.

You could wrap your function around that code, replacing the hard values with parameters.

这篇关于函数将从形状参数为alpha且速率参数为beta的伽玛分布中生成大小为n的迭代样本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆