I'm trying to make different lm models using the same data, but show higher order interactions by changing the exponent. I'm trying to make this in a for loop rather than writing multiple lines. But I'm getting an "invalid power in formula" error.
for (m in 1:5){
assign(paste("lm.", m, sep = ""), lm(paste("Response ~ (Factor1+Factor2+Factor3+Factor4+Factor5)^", m, sep = "")))
}
Q: What is causing this and how do I fix it?
Secondly, I would like to have the number of factors in the lm function (Factor1+Factor2+...) be pasted in, as the number of Factors changes.
I also have not been able to see if this works yet due to the above error.
I tried:
for (m in 1:n.factors){
# Make a string to paste in lm()
assign(paste("lm.paste.", m, sep = ""), paste("Response ~ (", paste(factors, collapse="+"), ")^", m, sep = ""))
# Paste in string to lm()
assign(paste("lm.", m, sep = ""), lm(lm.paste.1, data=data.df))
}
Where "factors" is a vector containing strings of my factors ("Factor1", "Factor2" ...). And n.factors is the number of factors.
Q: Is this the correct way of doing this? It feels a little cumbersome.
Maybe there is some way to use
lm(Response ~ ., data = data.df)
And subset the .?
Here is My Data Frame.
Edit:
dput(head(data.df, 20))
structure(list(Factor1 = c(-1, 1, -1, 1, -1, 1, -1, 1, -1, 1,
-1, 1, -1, 1, -1, 1, -1, 1, -1, 1), Factor2 = c(-1, -1, 1, 1,
-1, -1, 1, 1, -1, -1, 1, 1, -1, -1, 1, 1, -1, -1, 1, 1), Factor3 = c(-1,
-1, -1, -1, 1, 1, 1, 1, -1, -1, -1, -1, 1, 1, 1, 1, -1, -1, -1,
-1), Factor4 = c(-1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 1, 1,
1, 1, 1, 1, -1, -1, -1, -1), Factor5 = c(-1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 1, 1), Response = c(680.45,
722.48, 702.14, 666.93, 703.67, 642.14, 692.98, 669.26, 491.58,
475.52, 478.76, 568.23, 444.72, 410.37, 428.51, 491.47, 607.34,
620.8, 610.55, 638.04), Order = c(17, 30, 14, 8, 32, 20, 26,
24, 10, 16, 27, 18, 3, 19, 31, 15, 12, 1, 4, 23)), .Names = c("Factor1",
"Factor2", "Factor3", "Factor4", "Factor5", "Response", "Order"
), row.names = c(NA, 20L), class = "data.frame")