[R] Q re iterating a process and appending results to output file

Eric C Banfield ECB2 at ntrs.com
Wed Jul 23 20:47:56 CEST 2008


Greetings.  This is very basic but we can't figure it out.  The following
simple code counts how many values land in the "tail" (below a quantile) of
a standardized normal distribution of random numbers.  First two commands
are inputs:
> c <-0.05
> i <-2500
Second two commands are formulas I want to repeat many times (sort of like
an Excel/VBA macro) using those same inputs:
> r <- rnorm(i,0,1)
> n <- length(r[r<qnorm(c)])

I believe I could also run this as one line: r <- rnorm(i); n <-
length(r[r<qnorm(c)])

"n" will vary around 125.  Each time I run the code -- say 262 times --
I'll get a new "n".  I want to save all those "n"s in a file for Excel.

I can use cat(n,file="c:/temp/file.csv") to store the value of n in a *.csv
file.  But:

1. How do I tell R each time I run the above to append in that file the new
value of 'n' to the list of prior 'n's?
e.g., Suppose the first run I get n=125, second run I get n=127, and so on.
I want a file that will have 125 in the first row, 127 the second, and so
on,
I tried cat(n,file="c:/temp/file.csv", sep=" ") but it holds only the
single, latest value of n.
I tried file.append but then I get 125127.

2.  How do I tell R to run or loop through the above lines hundreds of
times, e.g., j = 262? -- rather like an Excel/VBA macro?)
So if I can make this iterate 262 times, I'll have a list or column of 262
numbers.

Thanks -- Eric.



More information about the R-help mailing list