Reputation: 350
I was hoping to get lm() to accept a character string as formula input but it does not quite work. This works so far:
Test<-as.data.frame(matrix(sample(1:100, 12), 4, 3))
colnames(Test)<-c("Y", "X1", "X2")
lm(Y~X1, data=Test)
XT1<-"X1"
lm(Y~eval(parse(text=XT1)), data=Test)
This works fine and produces the correct output. However, when I trie to have more than one parameter:
lm(Y~X1+X2, data=Test)
XT2<-"X1+X2"
lm(Y~eval(parse(text=XT2)), data=Test)
This does not produce the same result. I wonder why since obviously the character strings are both interpreted correctly:
parse(text=XT1)
parse(text=XT2)
For the background: In the end this should work in a function, where a matrix of parameters is supplied and the XT2 string should be dynamically created from the colnames of the matrix, so I'd need a solution that works with XT2 of all possible lengths between 1 and (hypothetically) infinity.
Upvotes: 3
Views: 1926
Reputation: 563
with eval(parse(x)) you execute the string x as code, so in this case you first add X1 and X2 creating 1 variable and then run the regression.
Upvotes: 2
Reputation: 132576
Do not use eval(parse())
until you are an advanced R user (and then you usually won't need it). Just use as.formula
:
lm(as.formula(paste0("Y ~ ", XT2)), data=Test)
Note that a better strategy for your goal would be:
lm(Y ~ ., data=Test[, c("Y", "X1", "X2")])
Upvotes: 8