[R] Q re iterating a process and appending results to output file
jim holtman
jholtman at gmail.com
Wed Jul 23 21:56:01 CEST 2008
Here is one way of doing it:
# generate 200 x 2500 samples and then check them
c <- qnorm(0.05)
i <- 2500
iter <- 200
x <- matrix(rnorm(i * iter, 0, 1) < c,nrow=i) # TRUE/FALSE according
to condition
# now create the counts
x.c <- colSums(x)
# write out to a file 1 value on each line
cat(x.c, file='/tempxx.txt', sep="\n")
On Wed, Jul 23, 2008 at 2:47 PM, Eric C Banfield <ECB2 at ntrs.com> wrote:
>
> 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.
>
--
Jim Holtman
Cincinnati, OH
+1 513 646 9390
What is the problem you are trying to solve?
More information about the R-help
mailing list