1

From these strings

data = "mtcars"
y    = "mpg"
x    = c("cyl","disp")

, I am trying to perform a linear model. I tried things like

epp=function(x) eval(parse(text=paste0(x,collapse="+")))

lm(data=epp(data),epp(y)~epp(x))
# Error in eval(expr, envir, enclos) : object 'cyl' not found

where the last line was aimed to be equivalent to

lm(data=mtcars,mpg~cyl+disp)
Remi.b
  • 17,389
  • 28
  • 87
  • 168
  • You're going to get a flood of people telling you to just not do this at all, unless you provide some detailed context, which I'm going to guess involves some sort of application that solicits data, x and y arguments from a user and then runs a linear model? Explaining that context will probably head off misunderstandings and probably lead to better answers. – joran Oct 22 '16 at 15:59
  • @joran My goal is to make a function that performs stepwise model selection for MCMCglmm. – Remi.b Oct 22 '16 at 16:13
  • In that case it seems awfully strange that you'd be passing a character representation of the data frame name, rather than the object itself. – joran Oct 22 '16 at 16:17
  • Yes, you are right for the data.frame. The reason was (1) partially for the purpose of learning and (2) to not have to copy the whole data.frame when passed to the function (but the copy time is quite negligible anyway). I have now changed it. – Remi.b Oct 22 '16 at 16:38

1 Answers1

4

This involves two operations that are both described in multiple SO entries that use perhaps singly either the get or as.formula functions:

lm(data=get(data), 
   formula=as.formula( paste( y, "~", paste(x, collapse="+") ) )
  )

In both cases you are use a text/character object to return a language object. In the first argument get returns a 'symbol' that can be evaluated and in the second instance as.formula returns a 'formula' object. @blmoore is correct in advising us that lm will accept a character object, so the as.formula call is not needed here.

IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • Beat me to it! You can even let `lm` do the coercion to formula from character – blmoore Oct 22 '16 at 16:01
  • @Remi.b: The Guardian of R Purity counsel us to avoid using `eval(parse(...` because it usually a method to cast R in a macro-processing mode of programming. To `blmoore`: I didn't realize that NSE had descended into `lm` processing of character values, but I guess it doesn't really create any ambiguity. – IRTFM Oct 22 '16 at 16:01