3

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

jogo
  • 12,469
  • 11
  • 37
  • 42
user11607046
  • 177
  • 4
  • 10
  • 3
    Try `rchisq(100000, df = 3)` – Darren Tsai Jun 05 '20 at 11:26
  • Thank you! can I know why dchisq does not work? – user11607046 Jun 05 '20 at 12:08
  • Straight from the help pages, `dchisq gives the density, ..., and rchisq generates random deviates.` dchisq was giving you the density for the points 1:100000 you specified rchisq is giving you 100000 random draws. You may want to use `rchisq(n = 100000, df = 3)` which is clearer and identical to 1:100000 in outcome – Chuck P Jun 05 '20 at 12:23

3 Answers3

3

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.

Roland
  • 127,288
  • 10
  • 191
  • 288
1

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

Len Greski
  • 10,505
  • 2
  • 22
  • 33
1

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

jay.sf
  • 60,139
  • 8
  • 53
  • 110