Re: [R] generating an expression for a formula automatically

From: Maria Montez <montez_at_bu.edu>
Date: Tue 29 Aug 2006 - 05:51:24 EST

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.
>
>
>
>



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Tue Aug 29 07:06:45 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Tue 29 Aug 2006 - 10:24:52 EST.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.