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

Rick Bilonick rab at nauticom.net
Thu Oct 25 08:12:52 CEST 2007


On Thu, 2007-10-25 at 15:34 +1000, Bill.Venables at csiro.au wrote:
> 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
> 

Thanks. The problem with this approach is that the data.frame variable
names are lost. (A minor point is that it won't work if only one
variable is chosen.) The function I wrote generates labels for a plot
and I want the variable name to show up (not "i"). I was hoping not to
have to re-write my function. Is there a way to pass the variables that
will allow my function to work normally (just as it would if I wrote out
the function calls with the names manually inserted)? (I would assume
that any function that generates a character variable from the variable
name is not going to produce the desired result.)

Rick B.



More information about the R-help mailing list