2

I am not able to resolve the issue that when lm(sformula) is executed, it does not show the string that is assigned to sformula. I have a feeling it is generic way R handles argument of a function and not specific to linear regression.

Below is the illustration of the issue through examples. Example 1, has the undesired output lm(formula = sformula). The example 2 is the output I would like i.e., lm(formula = "y~x").

x <- 1:10
y <- x * runif(10)
sformula <- "y~x"

## Example: 1 
lm(sformula)

## Call:
## lm(formula = sformula)

## Example: 2
lm("y~x")

## Call:
## lm(formula = "y~x")
Zheyuan Li
  • 62,170
  • 17
  • 162
  • 226
  • @Zheyuan, In a way you can say that. Actually I am defining few modules, one for source that provides data and formula. The other modules can then create all the objects - response vector, predictors dataframe/matrix in proper format needed for the model algorithm. This way the module handling model processing remains independent of the raw source data. – Mahesh Yadav Jul 25 '16 at 02:13

1 Answers1

5

How about eval(call("lm", sformula))?

lm(sformula)
#Call:
#lm(formula = sformula)

eval(call("lm", sformula))
#Call:
#lm(formula = "y~x")

Generally speaking there is a data argument for lm. Let's do:

mydata <- data.frame(y = y, x = x)
eval(call("lm", sformula, quote(mydata)))
#Call:
#lm(formula = "y~x", data = mydata)

The above call() + eval() combination can be replaced by do.call():

do.call("lm", list(formula = sformula))
#Call:
#lm(formula = "y~x")

do.call("lm", list(formula = sformula, data = quote(mydata)))
#Call:
#lm(formula = "y~x", data = mydata)
Zheyuan Li
  • 62,170
  • 17
  • 162
  • 226
  • The example I quoted was simplistic. Since I plan to do for generic models. Your recipe will make my code difficult to manage. I was more looking in line with I() function which will instruct the lm function to substitute with string variable. Thanks for the suggestion anyway. – Mahesh Yadav Jul 25 '16 at 02:40
  • I will accept `do.call` as answer to my question. However it is less likely that I will implement in the code due to the baggage for modelling in gbm and randomForest. Nevertheless, I learnt a practical application of `do.call()` which will be useful in future. Thanks! – Mahesh Yadav Jul 25 '16 at 03:59