Reputation: 125
i try to write a program in r "generate a random sample from any distribution using function". but it shows "Error in hist.default(xbars) : 'x' must be numeric" my program is here
sim.clt <- function(n, ran.func,..., simsize,...)
{
xbars<-vector()
for(i in 1:simsize=simsize)
{
x<-function(ran.func)
xbars[i]<-mean(x)
}
par(mfrow=c(2,1))
hist(xbars)
qqnorm(xbars)
return(xbars)
}
sim.out<-sim.clt(n=20,ran.func="rexp",simsize=5000)
shapiro.test(sim.out)
i am new in r programming, so can't figure it out, how to solve the problem. thanks...
Upvotes: 0
Views: 1411
Reputation: 174898
There are lots of things wrong here.
for(i in 1:simsize=simsize)
should be throwing an error:
> for(i in 1:simsize=simsize) { print(i)}
Error: unexpected '=' in "for(i in 1:simsize="
Better is
for(i in seq_len(simsize))
Then
x <- function(ran.func)
is not doing what you thought it was; it is returning a function with xbars[i]<-mean(x)
as its body, as in:
> x <- function(ran.func)
+
+ xbars[i]<-mean(x)
> x
function(ran.func)
xbars[i]<-mean(x)
> is.function(x)
[1] TRUE
I think you wanted to call ran.func
so you may need
FUN <- match.fun(ran.func)
x <- FUN()
But that will fail because you don't seem to be passing any argument for ran.func
to work, even just n
in the example using rexp
.
The error message stems from this last point. You defined xbars
to be the empty vector()
, which by default created an empty logical vector:
> xbars <- vector()
> xbars
logical(0)
> is.numeric(xbars)
[1] FALSE
Now, this wouldn't have been a problem if you hadn't made the error in defining x
(recall xbars[i]<-mean(x)
is now in the body of the function x
and has never been explicitly called), which means xbars
remains a empty logical vector. As that is not numeric, hist
throws the error you are seeing.
Another error is that you can't use ...
in the function definition twice. Are you trying to have the first contain arguments to pass to ran.func
and the second ...
to be for something else. You just can't do that in R.
Is this what you wanted?
sim.clt <- function(n, ran.func, simsize, ...) {
## ... passed to ran.func for other parameters of distribution
xbars <- numeric(simsize)
for(i in seq_len(simsize)) {
FUN <- match.fun(ran.func)
x <- FUN(n = n, ...)
xbars[i] <- mean(x)
}
## plot
op <- par(mfrow=c(2,1))
on.exit(op)
hist(xbars)
qqnorm(xbars)
xbars
}
> sim.out<-sim.clt(n=20,ran.func="rexp",simsize=5000)
> shapiro.test(sim.out)
Shapiro-Wilk normality test
data: sim.out
W = 0.9867, p-value < 2.2e-16
Upvotes: 6