lyashee
lyashee

Reputation: 1

My function isn't recognized by my loop

I am trying to sample a population drawn from a normal distribution with a mean of 10.016 and a standard deviation of 0.8862719 (n=20), a thousand times. I want to create a loop to do this. I tried creating a function (stamendist) to draw random variables from a normal distribution with the abovementioned mean and standard deviation, but when I run the loop, I get an error message: Error: could not find function "stamendist" (even though I ran the function before running the loop).

I tried running the loop without the object "stamendist" by just inputting rnorm(n=20,mean=10.016,sd=0.8862719), but the same error message persists.
Here is my code:

stamendist <- rnorm(n=20,mean=10.016,sd=0.8862719)
sampled.means <- NA 

for(i in 1:1000){
    y=stamendist(100)
    sampled.means[i] <- mean(y)
}

Am I misunderstanding how a function works? I'm pretty new to R, so any help or advice would be appreciated.

Upvotes: 0

Views: 63

Answers (3)

Sven Hohenstein
Sven Hohenstein

Reputation: 81683

You don't need a loop to obtain the vector of sample means:

n <- 1000
sampled.means <- colMeans(matrix(rnorm(n = 20 * n, 10.016, 0.8862719), ncol = n))

Upvotes: 3

cdeterman
cdeterman

Reputation: 19960

If you want stamentdist to be a function, you need to assign stamendist as a function. The general notation for a function is:

foo <- function(args, ...){
    expressions
}

You must then decide which parameters you want the user to specify. In your specific example, I assume you want the user to specify how many observations. Here is how the function would look with that in mind:

stamendist <- function(n) {
  rnorm(n=n,mean=10.016,sd=0.8862719)
}

Upvotes: 1

cowls
cowls

Reputation: 24334

In this line:

stamendist <- rnorm(n=20,mean=10.016,sd=0.8862719)

You assign 20 values to the vector named stamendist

In this line:

y=stamendist(100)

You try to call a function stamendist, which doesnt exist.

Move this lineinside the loop:

stamendist <- rnorm(n=20,mean=10.016,sd=0.8862719)

So you create a new set of random number for each iteration. Then pass stamendist to the mean function. And you dont need y at all

Upvotes: 0

Related Questions