3

I am working on a data set where I have to generate formula to be passed to lm dynamically. So, I am using reformulate to do this.

formula = reformulate(termlabels = c('feature1', 'feature2', 'feature3'), response="y")

y is continuous.

This gets me the formula as y ~ feature1+feature2+feature3

However I want the formula to be log(y+1) ~ feature1+feature2+feature3

How do I do this using reformulate?

pramodh
  • 1,259
  • 1
  • 14
  • 29

1 Answers1

9

Pass in the response as a quoted expression:

x <- c("feature1", "feature2", "feature3")
reformulate(x, response=quote(log(y+1)))

Or you could just construct the formula manually. This is what reformulate does under the hood.

formula(paste("log(y + 1) ~", paste(x, collapse="+"))) 
Hong Ooi
  • 56,353
  • 13
  • 134
  • 187
  • I would have guessed that `as.formula` would be used for the second strategy. – IRTFM Oct 15 '14 at 04:43
  • 1
    what if you use reformulate in a loop and need to do something such as log(var) , where var = dat[,i]? In this case, var is just an object standing in for the actual variable name (an therefoe the baove doesn't work). – theforestecologist Nov 20 '15 at 18:19