Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201945

How to sample a normally distributed population with a set mean and standard deviation multiple times

$
0
0

For demonstrations purposes, I want to sample 30 random observations from a normal distribution with a mean of 0 and a standard deviation of 2. I want to sample this "population" 10 times, so I will end with 300 observations and 10 groups. The following code works, but it repeats the same numbers. I want different numbers each time it iterates.

samp<-rep(c(1:10),each = 30)
obs <- tibble(observations=rep(c(rnorm(30, mean = 0, sd=2)), times = 10))

I do understand that I could just sample 300 random numbers, but the point I wish to illustrate deals with sampling populations. How can I change the previous code to do this?

I also want to plot the mean with error bars (using standard deviation) of each sampling routine (using ggplot2) as shown below. Is there a way to coerce the above operations (or one that produces different numbers upon each iteration) with the ones below and achieve the same results?

results<-
  data%>%
  group_by(samp)%>%
  summarize(avg = mean(data$obs),
              stdev = sd(data$obs))

plot<- 
  ggplot(results, aes(x=samp, y=avg, group=samp, color=samp)) + 
  geom_line() +
  geom_point()+
  geom_errorbar(aes(ymin=avg-stdev, ymax=avg+stdev), width=.2,
                 position=position_dodge(0.05))
print(plot)

Viewing all articles
Browse latest Browse all 201945

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>