Function that will generate iter samples of size n from a gamma distribution with shape parameter alpha and rate parameter beta

…衆ロ難τιáo~ 提交于 2020-01-25 08:34:06

问题


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

This is what I have:

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.

Thank you for your time.

Edit:

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

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


回答1:


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.



来源:https://stackoverflow.com/questions/58964331/function-that-will-generate-iter-samples-of-size-n-from-a-gamma-distribution-wit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!