# How to generate a binomial sample and plot histogram using R

#### sdurrington

##### New Member
How do you generate a histogram using sample size of 1000 from a bin(50,0.8) distribution. I've found this hist() function but not sure how to get the bin distribution into R ?

#### TheEcologist

##### Global Moderator
How do you generate a histogram using sample size of 1000 from a bin(50,0.8) distribution. I've found this hist() function but not sure how to get the bin distribution into R ?
Here's how you can do it:

#create a place to store your resamples
histdat=rep(NA,1000)
#loop
for(i in 1:1000){
histdat=sum(sample(c(0,1),50,replace=T,prob=c(0.2,0.8)))
}
#plot
hist(histdat,breaks=seq(30,50,1))

#Check with theorectical curve
lines(seq(30,50,1),dbinom(seq(30,50,1),50,0.8)* 1e+3 ,col="green")

#seems to have worked!

Good luck,

#### vinux

##### Dark Knight
Nice One Ecologist. I love the graphical part.
Here is another way, using the function directly.
See the code below.
Code:
bindat<-rbinom(1000,50,.8)

#plot
hist(bindat,breaks=seq(30,50,1))

#Check with theorectical curve
lines(seq(30,50,1),dbinom(seq(30,50,1),50,0.8)* 1e+3 ,col="green")

#### TheEcologist

##### Global Moderator
Nice One Ecologist. I love the graphical part.
Here is another way, using the function directly.
See the code below.
Code:
bindat<-rbinom(1000,50,.8)

#plot
hist(bindat,breaks=seq(30,50,1))

#Check with theorectical curve
lines(seq(30,50,1),1e+3*dbinom(seq(30,50,1),50,0.8),col="green")
Yep, that works perfectly too. It's superiour because it's less code (more of a "blackbox" though)

I needed to increase the range of the breaks to get it to work though:

hist(rbinom(1000,50,.8),breaks=seq(20,60,1),xlab="N successes")
lines(seq(20,60,1),1e+3*dbinom(seq(20,60,1),50,0.8),col="green")