On Wed, Jun 29, 2011 at 11:42 AM, Simon Goodman <s.j.good...@leeds.ac.uk> wrote: > I have 2 related questions about functions. > > 1. I am writing a function to plot data from a time series with the form > > myplot<-function(data, d1,d2) { } > > Where d1 and d2 are two dates in a time series. The idea being that if no > values for d1 and d2 are entered then the function defaults to plotting the > whole time series, else it plots the data for the interval specified by d1 > and d2. > > I am attempting to test if the variable d1 has been inputted by using a > different function, orginally posted on a R help forum by Brian Ripley. > > testObject <- function(object) > { > exists(as.character(substitute(object))) > } > > here testObject(x) returns FALSE if x is not currently present a variable in > the work space image. > > testObject works fine outside my plotting function, but not within it.... it > always returns FALSE inside the plotting function even when d1 is being > given by the user. > > I get the same result even if the testObject function is defined inside the > plotting function.... > > I suspect this may be due to enviroment being searched for d1.... but can't > find work out how to make it search for d1 within the 'myplot' function - I > think this can done using 'where' or 'environment' - but the documentation > on these commands is a little opaque. > > 2. For the 'myplot' function I would also like to add a customlegend=TRUE > (or FALSE) option, which determines if a custom legend is plotted (if not > inputted it would default to TRUE), but haven't been able to find anything > on how to specify this kind TRUE/FALSE of option for functions. >
Try this: We can just forward the first 1-3 arguments to window like this: my.plot <- function(..., customlegend = TRUE) { plot(window(...)) if (customlegend) legend("topleft", leg = "My custom legend") } tt <- ts(1:10) # example 1 my.plot(tt, 3, 6) # example 2 myplot(tt) -- Statistics & Software Consulting GKX Group, GKX Associates Inc. tel: 1-877-GKX-GROUP email: ggrothendieck at gmail.com ______________________________________________ R-help@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.