[R] string evaluation

David Winsemius dwinsemius at comcast.net
Sat Mar 12 16:22:02 CET 2011


On Mar 12, 2011, at 10:10 AM, Wensui Liu wrote:

> Good morning, dear listers
>
> I am wondering how to do string evaluation such that
>
> model <- glm(Y ~ [STRING], data = mydata) where STRING <- "x1 + x2 +  
> x3"
>
> It is very doable in other language such as SAS.

Also "very doable" in R. You need to understand that R is a bit more  
structured than SAS, which is really just a macro-processor at least  
by heritage. Formulas are a language class in R and not just character  
vectors,  so you need to construct them outside the regression  
functions.

STRING <- "x1 + x2 + x3"
form <- formula(paste("Y ~ ", STRING) )
  form
# Y ~ x1 + x2 + x3
  class(form)
#[1] "formula"

  model <- glm(form, data = mydata)

-- 
David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list