What is the algorithm of rchisq() function in R?
I am trying to build my myrchisq(), can anyone build the function that will give me the same result as rchisq()?
Note: I don't need ncp = 0
I just need myrchisq = function(n, df){}
I will develop the function using the help of rnorm() function in R. I will assume the non- centrality parameter as 0.
Following is the code. If you run the code, you will get the answer.
###############################################################################
library(MASS)
mychisq=function(sampsize,df)
{
rs=array(dim=1)
for(i in 1:sampsize)
{
x=mvrnorm(1,mu=rep(0,df),Sigma=diag(1,df))
rs[i]=t(x)%*%x
}
return(rs)
}
#To compare mychisq() with rchisq()
par(mfrow=c(1,2))
hist(mychisq(10000,5),freq=F)
hist(rchisq(10000,5),freq=F)
############
After running the code, we will see that both are giving same histogram.
If you do not get anything in this solution, please put a comment and I will help you out. Do not give a downvote instantly. It is a humble request. If you like my answer, please give an upvote.
Get Answers For Free
Most questions answered within 1 hours.