Generate random numbers of a chi squared distribution in R

Viewed 3089

I want to generate a chi squared distribution with 100,000 random numbers with degrees of freedom 3.

This is what I have tried.

df3=data.frame(X=dchisq(1:100000, df=3))

But output is not I have expected. I used below code to visualize it.

ggplot(df3,aes(x=X,y=..density..)) + geom_density(fill='blue')

Then the pdf looks abnormal. Please help

3 Answers

Use rchisq to sample from the distribution:

df3=data.frame(X=rchisq(1:100000, df=3))
ggplot(df3,aes(x=X,y=..density..)) + geom_density(fill='blue')

resulting plot

If your goal is to plot a density function, do this:

ggplot(data.frame(x = seq(0, 25, by = 0.01)), aes(x = x)) + 
  stat_function(fun = dchisq, args = list(df = 3), fill = "blue", geom = "density")

resulting plot

The latter has the advantage of the plot being fully deterministic.

Use rchisq() to create a distribution of 100,000 observations randomly drawn from a chi square distribution with 3 degrees of freedom.

df3=data.frame(X=rchisq(1:100000, df=3))
hist(df3$X)

...and the output:

enter image description here

The ggplot version looks like this:

library(ggplot2)
ggplot(data = df3, aes(X)) + geom_histogram()

enter image description here

You may use rchisq to make random draws from a random X2 distribution as shown in the other answers.

dchisq is the density distribution function, which you might find useful though, since you want to plot:

curve(dchisq(x, 3), xlim=0:1*15)

enter image description here

Related