Suppose I have 4 variables in R that belong to dataset data1 and are named x1, x2, y1, y2, and I want to use a loop to create the following variables zi = xi*yi for i=1,2 that will also belong to data1. These variables are defined as follows:
I was previously coding it as
data1$x1<-c(1,2,3)
data1$x2<-c(2,3,4)
data1$y1<-c(3,4,5)
data1$y2<-c(4,5,6)
I was previously coding the process as
data1$z1<-data1$x1*data1$y1
data1$z2<-data1$x2*data1$y2
This might seem practical for creating only two new variables, but I want to learn how to use a loop for situations where there are many more variables to create with this pattern.
I have tried searching online without success because I don't really know what to search. I know for the creating new variables I can use the paste0 and assign functions, but I am not sure how to reference existing variables using a loop index.
Any help is much appreciated!