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

Gabor Grothendieck ggrothendieck at gmail.com
Sun Oct 12 14:24:07 CEST 2008


On Sun, Oct 12, 2008 at 7:32 AM, Barry Rowlingson
<b.rowlingson at lancaster.ac.uk> wrote:
> 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.

To avoid the comma problem just have one alternative
that specifies them all and make sure only the desired
line is uncommented:

# VarNames <- c("a", "b", "c")
# VarNames <- "a"
VarNames <- :"b"
# VarNames <- "c"

>
>  Of course the real way to do it is to rewrite it as a function and do
> foo(c("Var1","Var2")) as desired....
>
> Barry
>
> ______________________________________________
> 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.
>



More information about the R-help mailing list