[R] Executing a Function in a Loop With a ChangingValue foran Argument

Rick Bilonick rab at nauticom.net
Thu Oct 25 15:52:41 CEST 2007


On Thu, 2007-10-25 at 16:26 +1000, Bill.Venables at csiro.au wrote:
> I wondered if the real problem was bigger than your abstract version.
> OK.  Here is one way to do it
> 
> > myfunc <- function(x) {
>     nam <- deparse(substitute(x))
>     val <- mean(x)
>     cat("mean(", nam, ") =", val, "\n")
>     invisible(val)
>     }
> > ex <- quote(myfunc(x))
> > subst <- function(Command, ...) do.call("substitute", list(Command,
> list(...)))
> > dat <- data.frame(matrix(rnorm(25), 5, 5))
> > vars <- names(dat)[-1]
> > vars
> [1] "X2" "X3" "X4" "X5"
> > for(i in vars) with(dat, eval(subst(ex, x = as.symbol(i))))
> mean( X2 ) = -0.08661249 
> mean( X3 ) = 0.009840606 
> mean( X4 ) = -0.21054 
> mean( X5 ) = 0.07321301 
> > colMeans(dat[, -1])
>           X2           X3           X4           X5 
> -0.086612490  0.009840606 -0.210540008  0.073213012 
> > 
> 
> Now why do I suspect there is something more as well....hmmm...? 
> 
> 
> Bill Venables

Thanks. I'm sure I didn't explain it well but I did mention trying to
use "as.symbol" and problems with evaluation. I didn't have the words to
describe what exactly I was trying to do. Probably best to write a
simple version like you did (although the function I'm using isn't
complicated, it's just too long to serve as an example).

I modified your example so that I can see how it should work with my
actual function (I added one extra argument that doesn't need to
change):

myfunc <- function(y,x) {
    nam <- deparse(substitute(x))
    val <- mean(x)
    cat("mean(", nam, ") =", val,"y=",y, "\n")
    invisible(val)
    }
ex <- quote(myfunc(y,x))
subst <- function(Command, ...) do.call("substitute",
list(Command,list(...)))
dat <- data.frame(matrix(rnorm(25), 5, 5))
vars <- names(dat)[-1]
vars
for(i in vars) with(dat, eval(subst(ex, x = as.symbol(i),y=2)))

> myfunc <- function(y,x) {
+     nam <- deparse(substitute(x))
+     val <- mean(x)
+     cat("mean(", nam, ") =", val,"y=",y, "\n")
+     invisible(val)
+     }
> ex <- quote(myfunc(y,x))
> subst <- function(Command, ...) do.call("substitute",
list(Command,list(...)))
> dat <- data.frame(matrix(rnorm(25), 5, 5))
> vars <- names(dat)[-1]
> vars
[1] "X2" "X3" "X4" "X5"
> for(i in vars) with(dat, eval(subst(ex, x = as.symbol(i),y=2)))
mean( X2 ) = -0.6343765 y= 2 
mean( X3 ) = 0.4810482 y= 2 
mean( X4 ) = 0.5850177 y= 2 
mean( X5 ) = -0.006917436 y= 2 

Thanks again.

Rick B.



More information about the R-help mailing list