Rick Bilonick
2007-Oct-25 05:01 UTC
[R] Executing a Function in a Loop With a Changing Value for an Argument
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 manually: myfunc(x=var1) myfunc(x=var2) etc. 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 appreciated. Rick B.
Bill.Venables at csiro.au
2007-Oct-25 05:34 UTC
[R] Executing a Function in a Loop With a Changing Value foran Argument
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 checkX1 X2 X3 X4 X5 0.1779146 0.3648022 -0.1593466 0.5874517 -0.5049586>Bill Venables CSIRO Laboratories PO Box 120, Cleveland, 4163 AUSTRALIA 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 http://www.cmis.csiro.au/bill.venables/ -----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 Argument 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 manually: myfunc(x=var1) myfunc(x=var2) etc. 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 appreciated. Rick B. ______________________________________________ R-help at r-project.org 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.