[R] Stuck in trying to convert repetitive code into a function
Gabor Grothendieck
ggrothendieck at myway.com
Wed Mar 3 13:10:26 CET 2004
Issue the command:
debug(eat.a.file)
and then run your eat.a.file call. This will step you through
the function showing where it goes wrong.
By the way,
- you don't need semicolons at the end of each line,
- the format you are specifying on chron is the default anyways
so you can leave out format=
- if you give use the argument as.is=1 on read.table then it
will return the date column as a character so you can convert it
to character like this: A$date <- chron(A$date)
---
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