[R] Stuck in trying to convert repetitive code into a function
Ajay Shah
ajayshah at mayin.org
Tue Mar 2 19:00:10 CET 2004
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 at mayin.org Department of Economic Affairs
http://www.mayin.org/ajayshah Ministry of Finance, New Delhi
More information about the R-help
mailing list