[R] Saving a variable

Joshua Wiley jwiley.psych at gmail.com
Mon May 7 01:27:50 CEST 2012


Hi Trying,

Jim already suggested youuse write.table(), which I think is really
what you want.  I also wanted to point out that your outer loop is
unnecessary.  The following yields identical results and is *much*
faster.

randz <- matrix(rnorm(1000000), 500, 2000)
H <- matrix(0, 500, 2000)

H[1, ] <- randz[1, ]

for (i in 2:500){
  if(i < 251) {
    H[i, ] <- 0.6 * H[i-1, ] + randz[i, ]
  } else {
    H[i, ] <- H[i-1, ] + randz[i, ]
  }
}

write.table(H, file = "datad.txt")

There may be ways to optimize (or remove) the remaining loop, but at
least this first pass should move things along considerably.

Cheers,

Josh

On Sun, May 6, 2012 at 2:02 PM, Trying To learn again
<tryingtolearnagain at gmail.com> wrote:
> Hi all,
>
> I´m trying to use write function to save the output of a program (my
> constructed "H" matrix)
>
>
> randz<-matrix(rnorm(1000000),500,2000)
>
> H<-matrix(0,500,2000)
>
> H[1,]<-randz[1,]
>
> for (j in 1:2000){
> for (i in 2:500){
> if(i<251)
> H[i,j]<-0.6*H[i-1,j]+randz[i,j]
>
> else H[i,j]<-H[i-1,j]+randz[i,j]
>
> }}
>
> write(H, file = "datad.txt",2000)
>
> If I ommit the 2000 on write function it only puts 5 columns.
>
> The problem is that if I use this it seems it is not saving the same data I
> have simulated....or this seems to me.
>
> You see if I type H[,1] it is not the same that includen on the firs column
> on datad.txt?
>
> I feel very slow witted....
>
> Many thanks in advance for all
>
>        [[alternative HTML version deleted]]
>
>
> ______________________________________________
> 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.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
Programmer Analyst II, Statistical Consulting Group
University of California, Los Angeles
https://joshuawiley.com/



More information about the R-help mailing list