[R] generating an expression for a formula automatically

Maria Montez montez at bu.edu
Mon Aug 28 21:51:24 CEST 2006


Thank you for your responses.

Prof Ripley's code only worked for a vector with 2 variables but I need 
the code to work for a vector of any size. To solve this I created a for 
loop. I'm not sure this is the most efficient way of doing it but it works.

 x1 <- c(1,0,0,1)
 x2 <- c(0,0,1,1)
 x3 <- c(0,0,0,0)
 x4 <- c(1,0,0,1)
 data1 <- cbind(x1,x2,x3,x4)
 x <-  c("x1","x2","x3","x4")

do.sum <- function(x,env=parent.frame()) {
   s <- get(x[1],env=env)
   for(i in 2:length(x)) {
     s <- s + get(x[i],env=env)
  }
 }
totx <- do.sum(x)
data2 <- cbind(data1,totx)
data2

Maria

Prof Brian Ripley wrote:

>On Fri, 25 Aug 2006, Maria Montez wrote:
>
>  
>
>>Thank you for your answers yesterday. I now have another question!
>>
>>Suppose that instead of creating a formula for a regression model I 
>>simply wanted to add the variables. I believe I cannot use the 
>>as.formula anymore. Again I tried to use expression to no avail. I get 
>>an expression but I can't use it.
>>
>>fit.sum <- function(x) {
>>    fo <- expression(paste(x, collapse = "+"))
>>   eval( fo)
>>}
>>fit.sum(c("x1","x2"))
>>
>>Basically what I need is to learn how to use variables when what is 
>>given to me are their names (character list).
>>    
>>
>
>I think we do need to tell you that parse(text=) is how to turn a 
>character vector into an expression, although it is rarely a good way (see 
>the fortune in the 'fortunes' package about it) and you need to be careful 
>where you evaluate:
>
>fit.sum <- function(x) eval.parent(parse(text=paste(x, collapse = "+")))
>
>As an alternative, the answer to
>
>  
>
>>Basically what I need is to learn how to use variables when what is
>>given to me are their names (character list).
>>    
>>
>
>is most often 'get'.  So for two objects
>
>fit.sum2 <- function(x) {
>   env <- parent.frame()
>   do.call("+", lapply(x, get, envir=env))
>}
>
>but again you need to be careful where you get() from.
>
>
>  
>



More information about the R-help mailing list