Supposed that I have the following data:
a1 <- 1
a2 <- 2
a3 <- 3
In my actual data, I have way more variable and what I am aiming to do is create interaction variables between them and then put them into one big dataframe like this:
a1a1 <- a1*a1
a1a2 <- a1*a2
a1a3 <- a1*a3
a2a2 <- a2*a1
a2a3 <- a2*a2
a3a3 <- a3*a3
mydf <- data.frame(a1a1,a1a2,...)
I am certain I could use a forloop to accomplish what I want but I am horribly new to R and coding methodology altogether. My intuition tells me to do something along the lines of this:
n <- 3
j <- 3
for( i in 1:n) {
k <- 1
for( j in 1:k) {
aiaj <- ai*aj
#Not sure how to put into a data.frame for each variable
k <- k + 1
}
}
The way the loop is constructed, I believe it would make the variables a1a1,a1a2,a1a3 on the first iteration, on the second iteration it would make a2a2,a2a3, and then on the third iteration a3a3. I've tried this, and it doesn't work so I am hoping I can get some suggestions. Additionally, I have no idea how I would keep adding to the data.frame
lm(y ~ (a1+a2+a3)^2, data=data). If the function that you are trying to use accepts formulas. please take a look at the help page?formula