Skip to content

Instantly share code, notes, and snippets.

@koushikkhan
Created May 28, 2019 18:54
Show Gist options
  • Save koushikkhan/9e5d608d8ffc284476ad3989f3d6c32d to your computer and use it in GitHub Desktop.
Save koushikkhan/9e5d608d8ffc284476ad3989f3d6c32d to your computer and use it in GitHub Desktop.
# A class to generate sample from Gaussian Distribution
# mean, standard-deviation and sample size are being
# expected to come from the user
library(R6)
library(ggplot2)
GaussianSimulator <- R6Class("GaussianSimulatorClass",
public = list(
mu = NA,
sigma = NA,
n_sample = NA,
sample = NA,
initialize = function(mu, sigma, n_sample) {
# Object Initiator
# Args
# mu: mean of the distribution
# sigma: std. dev. of the distribution
# n_sample: size of the sample
self$mu <- mu
self$sigma <- sigma
self$n_sample <- n_sample
},
get_sample_size = function() {
# getter method
return (self$n_sample)
},
set_sample_size = function(size) {
# setter method
self$n_sample = size
},
generate_sample = function() {
# Generates the random sample
self$sample <- rnorm(self$n_sample, self$mu, self$sigma)
return (self$sample)
},
compute_stats = function() {
# Computes basic statistics of the sample
r <- list(sample.mean = mean(self$sample),
sample.sd = sd(self$sample))
return (r)
},
plot_histogram = function(binwidth) {
p <- qplot(self$sample, geom = "histogram",
breaks = seq(130, 200, binwidth),
colour = I("black"), fill = I("white"),
xlab = "X", ylab = "Count") +
stat_function(
fun = function(x, mean, sd, n, bw){
dnorm(x = x, mean = mean, sd = sd) * n * bw
},
args = c(mean = self$mu,
sd = self$sigma,
n = self$n_sample,
bw = binwidth)
)
return (p)
}
)
)
#### Implementation ####
sm <- GaussianSimulator$new(mu=165, sigma=6.6, n_sample=1000) #creates a new object of the class
r <- sm$generate_sample() #generates a random sample
basic.stats <- sm$compute_stats() #computes basic statistics of the sample
p <- sm$plot_histogram(binwidth=2) #creates the histogram of the sample
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment