[R] sink() within a loop
Nordlund, Dan (DSHS/RDA)
NordlDJ at dshs.wa.gov
Wed Nov 5 19:48:26 CET 2008
> -----Original Message-----
> From: r-help-bounces at r-project.org
> [mailto:r-help-bounces at r-project.org] On Behalf Of jgarcia at ija.csic.es
> Sent: Wednesday, November 05, 2008 10:19 AM
> To: Uwe Ligges
> Cc: r-help at r-project.org
> Subject: Re: [R] sink() within a loop
>
> Well, I'll put a foo example of my problem:
>
> I'got a list:
>
> >a <- list()
> >a$sublist.1 <- list()
> >a$sublist.1$subsublist.1 <- list()
>
> this code works:
>
> >zz <- file("foo.txt","w")
> >sink(zz)
> >a
> >sink()
> >close(zz)
>
> and generates a correct "foo.txt" file containing the
> structure of the list
>
> but this code doesn't:
>
> >for(i in 1){
> zz <- file("foo.txt","w")
> sink(zz)
> a
> sink()
> close(zz)
> }
>
> as the resulting "foo.txt" file is empty
>
> I don't understand why.
>
> Javier
> ---------------------
> >
> >
> > jgarcia at ija.csic.es wrote:
> >> Hello;
> >> It seems to me that this could even by a FAQ, but I cannot find an
> >> answer:
> >>
> >> Why a piece of code that uses sink() does not sinks
> anything if it is
> >> executed within a for loop?
> >
> > Without sink(), does it print anything in the console? If not: use
> > print() in order to print it (i.e. sink it to another connection).
> >
> > Uwe Ligges
> >
> >
> >>
> >>
> >> Thanks,
> >> Javier
> >>
Javier,
Uwe gave you the answer. You need to explicitly print your variable as otherwise it will not be output to the console (and available to be be sunk). The same would be true if you were doing this inside a function. For example:
for(i in 1){
zz <- file("foo.txt","w")
sink(zz)
print(a)
sink()
close(zz)
}
One other comment. If you are actually going to do this inside a loop with multiple iterations, you will need to either change the file name on each iteration, or set the parameter append=TRUE, or you will overwrite data from the previous iterations.
Hope this is helpful,
Dan
Daniel J. Nordlund
Washington State Department of Social and Health Services
Planning, Performance, and Accountability
Research and Data Analysis Division
Olympia, WA 98504-5204
More information about the R-help
mailing list