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

From: Eric C Banfield <ECB2_at_ntrs.com>
Date: Wed, 23 Jul 2008 13:47:56 -0500

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.

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. Received on Wed 23 Jul 2008 - 18:53:24 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 23 Jul 2008 - 21:32:54 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive