Question

I am a novice to R and I can’t figure out a solution to my problem.

Imagine that I have created three normally distributed variables, x, y and z (n=100 in each with a mean of 0 and a sd of 1). The variables are independent from each other (r~0). Then I create two new variables xz and yz (i.e the interaction between x, z and y, z.).

Now assume that I want to keep x and y fixed and randomly sample from z (or create a new z) before the interactions are computed and, after every new random sample from z, compute the interactions and calculate the correlation coefficient between them (for the sake of argument lets say I want to do this 100 times) and print the 100 correlations to a new datafile for further analysis. How to I achieve this?

Was it helpful?

Solution

Not really sure that this is what you are asking for. Give it a check.

x<-rnorm(100)
y<-rnorm(100)
z<-rnorm(100)
xz<-x*z
yz<-y*z

co<-data.frame(nrow=100, ncol=2)
for (i in 1:100){
  z[i]<-rnorm(1)
  xz[i]<-z[i]*x[i]
  yz[i]<-z[i]*y[i]
 co[i,]<-c(cor(z,x), cor(z,y))
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top