[R] Conditionally skip over "for(..){" and "}"??

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Sun Oct 12 13:32:31 CEST 2008


2008/10/12 Ted Harding <Ted.Harding at manchester.ac.uk>:
> Hi Folks,
> I'm wondering if there's a secret trick to achieve the following.
>
> I have some big code for analysis related to a named variable,
> which will be one of several in the columns of a dataframe, and
> I would like to be able to choose between a run for just one of
> these variables, or a run which loops over them all.
>
> So, for a single run, I could have the following kind of thing
> in a file code.R to be sourced by source("code.R"):
>
> # VarName <- "Var1"
>  VarName <- "Var2"
> # VarName <- "Var3"
> # VarName <- "Var4"
>
> ### CUT OUT LOOP
> # VarNames <- c("Var1","Var2","Var3","Var4")
> # for( VarName in VarNames ) {
>
> << Lots of code related to analysis of variable VarName >>
>
> ### CUT OUT END OF LOOP
> # }
>
> which would do the single case for Var2. A run for a different VarName
> would be done by editing the first block to select the new VarName.
>
> Now, when I want to run the loop over all VarNames, I could of course
> likewise edit the file so as to uncomment the code which follows the
> "CUT OUT ..." lines. But I would prefer to avoid having to do the
> latter, and am therefore wondering if there is some way to conditionally
> skip over those bits of code.

 What's the problem with doing a loop over a single VarName in
VarNames? I'd put something like:

 VarNames = c(
"Var1",
"Var2",
"Var3"
)

 at the start of my code for easy editing, and then if I only wanted
to do it for one VarName you can just do:

VarNames = c(
#"Var1",
"Var2"
#"Var3"
)

 - it's just a shame that R doesn't like trailing commas in c() calls,
which would make it even easier.

 Of course the real way to do it is to rewrite it as a function and do
foo(c("Var1","Var2")) as desired....

Barry



More information about the R-help mailing list