[R] Stuck in trying to convert repetitive code into a function

About this list Date view Thread view Subject view Author view Attachment view

From: Ajay Shah (ajayshah@mayin.org)
Date: Wed 03 Mar 2004 - 05:00:10 EST


Message-id: <20040302180010.GA15763@igidr.ac.in>

Folks,

I have the following repetitive code which works correctly:

   A = read.table(file="junior.csv", sep=",", col.names=c("date", "l"));
   A$date = chron(as.character(A$date), format="m/d/y");
   r.junior = levels2weeklyret(lastfriday, A$date, A$l);
   plot(A$date, A$l, type="l", col="red", main="Junior levels")
   z <- locator(1)

   A = read.table(file="kospi.csv", sep=",", col.names=c("date", "l"));
   A$date = chron(as.character(A$date), format="m/d/y");
   r.kospi = levels2weeklyret(lastfriday, A$date, A$l);
   plot(A$date, A$l, type="l", col="red", main="Kospi levels")
   z <- locator(1)

I tried to write it more nicely as follows:

   eat.a.file <- function(fn, label, lastfriday) {
     f = read.table(file=fn, sep=",", col.names=c("date", "l"));
     f$date = chron(as.character(f$date), format="m/d/y");
     plot(f$date, f$l, type="l", col="red", main=label);
     z <- locator(1);
     return(levels2weeklyret(lastfriday, f$date, f$l));
   }
   r.junior = eat.a.file(fn="junior.csv", label="Junior", lastfriday);
   r.kospi = eat.a.file(fn="kospi.csv", label="Kospi", lastfriday);

When I do this, I get this error at the first of the two function calls:

Error in vector("double", length) : negative length vectors are not allowed
Execution halted

I have tried hard to experiment with various ways of writing it, but
am truly stumped. Any ideas on what might be going wrong? I am new to
R and have only written a few functions so far.

On a slightly related note, what is the situation in R on passing by
reference versus passing by value? I looked at the standard docs and
they seem to insist that a function can only send back one return
value. How does a function send back multiple things that it has
created?

-- 
Ajay Shah                                                   Consultant
ajayshah@mayin.org                      Department of Economic Affairs
http://www.mayin.org/ajayshah           Ministry of Finance, New Delhi

______________________________________________ R-help@stat.math.ethz.ch mailing list https://www.stat.math.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html


About this list Date view Thread view Subject view Author view Attachment view

This archive was generated by hypermail 2.1.3 : Fri 23 Apr 2004 - 18:36:28 EST