Hi,

It seems to me that you could write a generic function myplot() and have different methods for each class of object (like plot does). Either S3 or S4 classes would do I think. Then it is only a matter of making each method work separately. In particular, the method for a formula could contain the with(data, ) construct to make all the variables accessible to the text() function.

HTH,

baptiste



On 4 Apr 2009, at 23:27, Derek Ogle wrote:

Sorry for posting this twice, but I still have not solved this problem
and am hoping for some assistance.



I am attempting to write a function that is flexible enough to respond
to the user providing a formula (with a data= argument) or not (similar to plot(x,y) versus plot(y~x,data=data)). I have found a method to work
with this in a simple case but am having trouble determining how to
"find" a variable from within the data= argument that is not part of the
formula.  The following code illustrates (I know that
plotrix::thigmophobe.labels() does what this function does) my problem
...





myplot <- function(x,y=NULL,data=NULL,label=NULL) {

 if (class(x)=="formula") {

   mf <- model.frame(x,data=data)

   x <- mf[,2]

   y <- mf[,1]

 }

 if (is.null(y)) stop("Y-axis variable is missing")

 plot(x,y)

 if (!is.null(label)) text(x,y,label)

}



# dummy data

df <-
data .frame(x=runif(10),y=runif(10),grp=factor(rep(c("Yes","No"),each=5))
)



# both calls work as expected

with(df,myplot(x,y))

myplot(y~x,data=df)



# only first works as I would hope

with(df,myplot(x,y,label=grp))

myplot(y~x,data=df,label=grp)



# this works but is clumsy

myplot(y~x,data=df,label=df$grp)





Any help with how to make this function recognize the "grp" variable in
"df" when using the formula without having to type "df$grp" when
supplying it to the "label=" argument would be greatly appreciated.
Thank you in advance.






        [[alternative HTML version deleted]]

______________________________________________
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.

_____________________________

Baptiste AuguiƩ

School of Physics
University of Exeter
Stocker Road,
Exeter, Devon,
EX4 4QL, UK

Phone: +44 1392 264187

http://newton.ex.ac.uk/research/emag

______________________________________________
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.

Reply via email to