[R] Executing a Function in a Loop With a Changing Value foran Argument

Bill.Venables at csiro.au Bill.Venables at csiro.au
Thu Oct 25 07:34:10 CEST 2007

There are many simple ways to do this, if I understand you correctly.
Here is an example

> dat <- data.frame(matrix(rnorm(25), 5, 5))
> names(dat)
[1] "X1" "X2" "X3" "X4" "X5"
> vars <- names(dat)[-1]
> vars
[1] "X2" "X3" "X4" "X5"
> myfunc <- function(x) print(mean(x))
> for(i in dat[, vars]) myfunc(x = i)
[1] 0.3648022
[1] -0.1593466
[1] 0.5874517
[1] -0.5049586
> colMeans(dat)  ## as a check
        X1         X2         X3         X4         X5 
 0.1779146  0.3648022 -0.1593466  0.5874517 -0.5049586 

Bill Venables
CSIRO Laboratories
PO Box 120, Cleveland, 4163
Office Phone (email preferred): +61 7 3826 7251
Fax (if absolutely necessary):  +61 7 3826 7304
Mobile:                         +61 4 8819 4402
Home Phone:                     +61 7 3286 7700
mailto:Bill.Venables at csiro.au

-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org]
On Behalf Of Rick Bilonick
Sent: Thursday, 25 October 2007 3:02 PM
To: R Help
Subject: [R] Executing a Function in a Loop With a Changing Value foran

I want to run a function in a loop and replace one of the arguments from
a large list each time through the loop. If I was writing it out


But I want to do this in a loop where x is replaced by a new name. 

Something like:

for(i in vars) { myfunc(x=i) }

where "vars" is a vector of names for items in a data.frame.

If I use "as.symbol" to create names, the evaluation never works
correctly. Is there a way to do this? Any suggestions would be

Rick B.

R-help at r-project.org mailing list
PLEASE do read the posting guide
and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list