[R] tricky problem with "if" function -
Matthew Keller
mckellercran at gmail.com
Tue Oct 2 00:57:36 CEST 2007
Hi all,
This question involves using a "for" loop to make a "decision" in a script.
I've written a rather intricate script, and near the start of it, I
want it either to do a loop (if a variable called "number.runs" > 1)
or not do a loop (if "number.runs" is 1). This is probably trivial but
I can't figure it out. Here's a self-contained example that gets at
the gist of what I'm looking for:
number.runs <- 1 #try it with number.runs <- 2 as well
if (number.runs==1) run.number <- 1
if (number.runs>1) for(run.number in 1:number.runs){
print(number.runs) #in the real script, lots happens in here
if(number.runs>1) }
I'd like the following to print "1" if number.runs==1, and print "1"
and then "2" if number.runs==2.
But the above syntax does not work. R returns a Syntax Error. This
probably has to do with the order of operations?
Then I thought I would get tricky and use an eval(parse()) statement:
if (number.runs==1) cat("run.number <- 1",file="temp")
if (number.runs>1) cat("for(run.number in 1:number.runs){",file="temp")
eval(parse(file="temp"))
print(number.runs) #in the real script, lots happens in here
if(number.runs>1) cat("}",file="temp")
eval(parse(file="temp"))
But R returns the following error:
Error in parse(file, n, text, prompt, srcfile, encoding) :
temp: syntax error, unexpected END_OF_INPUT, expecting '\n' or ';' or '}' at
2: for(run.number in 1:number.runs){
--
Matthew C Keller
Postdoctoral Fellow
Virginia Institute for Psychiatric and Behavioral Genetics
More information about the R-help
mailing list