[R] A structured output from for(i...)?

Peter Dalgaard P.Dalgaard at biostat.ku.dk
Thu Apr 19 11:42:39 CEST 2007


francogrex wrote:
> Hello I am using the "for (i...)" and a sink() into a file. But the output I
> am having is not arranged in either a vector or any other good structure. I
> would like to have the output in a file directly as a vector so that I do
> not have to edit the [1] and [6] etc and that the values are comma
> separated. Is there a way? Thanks.
>   
Well, perhaps replace print(....) with something involving dput(), or
cat(x, sep=","); cat("\n"), but  (paraphrasing Thomas Lumley) whenever
the solution involves going via the printed representation, you may need
to rethink the problem.
In particular, why do you want this in a text file in the first place?

e.g.

res <- lapply(1:26, function(i) x$V1[i]*x$V2[1:26])

gives you a nice list of results that you can work with later on, or you
can even do

m <- outer(x$V1[1:26], x$V2[1:26])

which gives you a matrix right away (and write.table() can print that as
CSV).

> Example data:
>
> x=read.table(file="pw.power.txt")
> for(i in 1:26){sink("pw.predict.txt",append=TRUE)
> print((x$V1[i]*x$V2[1:26]))
> sink()
> }
>
> The output is like that
>
> [1] 3.355638e-11 4.172354e-10 2.716469e-09 1.232176e-08 4.371243e-08
>  [6] 1.286392e-07 3.261277e-07 7.301315e-07 1.468560e-06 2.686579e-06
> [11] 4.509928e-06 6.990915e-06 1.004944e-05 1.343056e-05 1.670355e-05
> [16] 1.932102e-05 2.073859e-05 2.057033e-05 1.873071e-05 1.550436e-05
> [21] 1.149907e-05 7.478074e-06 4.122808e-06 1.820828e-06 5.777628e-07
> [26] 9.981781e-08
>  [1] 2.256961e-10 2.806274e-09 1.827063e-08 8.287463e-08 2.940043e-07
>  [6] 8.652112e-07 2.193495e-06 4.910773e-06 9.877352e-06 1.806960e-05
> [11] 3.033321e-05 4.702002e-05 6.759127e-05 9.033228e-05 1.123460e-04
> [16] 1.299508e-04 1.394852e-04 1.383535e-04 1.259804e-04 1.042804e-04
> [21] 7.734131e-05 5.029659e-05 2.772949e-05 1.224666e-05 3.885961e-06
> [26] 6.713622e-07...etc....
>
> What I would like to have is that it is arranged into a structure (vector,
> data.frame...)
> x=c(3.355638e-11, 4.172354e-10, 2.716469e-09, etc... )
>   


-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907



More information about the R-help mailing list