Short simulation example to show that the sample mean (x bar) is a random variable

Setting seed and creating sample

Sample 1

set seed, create sample with n=10, mean=20, and sd=2

set.seed(1)
sample1= rnorm(n= 10, mean= 20, sd= 2)
sample1
##  [1] 18.74709 20.36729 18.32874 23.19056 20.65902 18.35906 20.97486 21.47665
##  [9] 21.15156 19.38922

round mean to three decimals

round (mean (sample1), 3)
## [1] 20.264

Sample 2

set seed, create sample with n=10, mean=20, and sd=2

set.seed(2)
sample2= rnorm(n= 10, mean= 20, sd= 2)
sample2
##  [1] 18.20617 20.36970 23.17569 17.73925 19.83950 20.26484 21.41591 19.52060
##  [9] 23.96895 19.72243

round mean to three decimals

round (mean (sample2), 3)
## [1] 20.422

See that sample changes from sample to sample -> random

Create 100 samples with 10 values each

For loop -> 100 samples

sample_means= vector(mode= "numeric")

for(i in 1:100){
  set.seed(i)
  sample_means= c(sample_means, round (mean(rnorm(n= 10, mean= 20, sd= 2)), 2))
}

Plot results

plot (sample_means, xlab= "Sample", ylab= "Xbar", yaxt = "n")
axis(2, at=seq(18,22,0.5), labels=seq(18,22,0.5))
abline(h= 20)

Create 100 samples with 50 values each

For loop -> 100 samples

sample_means2= vector(mode= "numeric")

for(i in 1:100){
  set.seed(i)
  sample_means2= c(sample_means2, round (mean(rnorm(n= 50, mean= 20, sd= 2)), 2))
}

Plot results

plot (sample_means2, xlab= "Sample", ylab= "Xbar", yaxt = "n")
axis(2, at=seq(18,22,0.5), labels=seq(18,22,0.5))
abline(h= 20)