Hi Simon, 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.
The usual way to check whether an argument has been specified within a function is by using missing(). > 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. I'm not sure what the question is, exactly. You do something like: myfun <- function(whatever, customlegend=TRUE) { # name the argument, give it a default value plot(whatever) if(customlegend) { # do the custom legend stuff } else { # do whatever the other version is } invisible() } It's all a matter of passing arguments to your functions. If those aren't really what you were asking, then you might need to restate the questions. Sarah -- Sarah Goslee http://www.functionaldiversity.org ______________________________________________ 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.