I recently described in this space how to generate correlated predictors. What I didn’t show was how to take those correlated predictors and use them to generate some observed outcomes. Once we’ve learned how to do this, we can take this general idea and begin toying around with the structure of the data to see how it changes (or doesn’t change) our estimation process.
So, after having generated our predictors, we can then determine what the function is that will generate our observed values.
For instance, if we have three predictors, , , , we could define a linear equation to generate an outcome:
Changing the value of any will change the relationship between and Y. As before, is a ‘noise’ parameter that adds variability to the linear relationship.
As an example, let’s set:
Thus, our linear equation for Y is:
And recall that we can define the relationships between our predictors with a variance-covariance matrix as follows:
As last time, we will set and to not be correlated, and will be slightly correlated, and and to have a strong correlation.
Now we need to indicate the parameters for the linear function described above. We can store these parameters in a vector, and then multiply the values in that vector by the observed values for , , and , and use the
rnorm function to draw random observations from a normal distribution defined by the Equation 2 above.
Let’s break that second line down a little bit. The function
rnorm generates random numbers from a normal distribution described by a mean and a standard deviation. To use it, we need to give it the mean, the standard deviation, and .
We set to be the length of our predictors dataframe,
dim(dat). For the mean, we convert that same dataframe to a matrix
as.matrix(dat), and use the matrix multiplication operator
%*% to multiply this by our parameter vector. You’ll notice we also add a constant of 1, because we specified that the intercept should be 1 (see Equation 2). In other words, the code inside the argument for the mean is the r translation of the linear portion of Equation 2, . We also stated that the noise would come from a normal distribution, centered on zero with a standard deviation of five. We added this in the sd argument of
rnorm, and appears as a 5 at the very end.
To check how well the simulated data fits the function that generated it, we can fit a linear model. We should recover something close to out parameters indicated in Equation 2.
Having created a set of steps that will simulate data, we can now use these steps to investigate if there is any systematic problem when we, for example, change the degree to which two predictors are correlated.