[R] Working with and without formula in function
dogle
DOgle at NORTHLAND.EDU
Fri Apr 3 20:51:23 CEST 2009
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 illustrates my problem ...
# an illustrative function -- I know that plotrix::thigmophobe.labels() does
what this function does
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"
without having to type "df$grp" when supplying it to the "label=" argument
would be greatly appreciated. Thank you in advance.
--
View this message in context: http://www.nabble.com/Working-with-and-without-formula-in-function-tp22874005p22874005.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list