On 16/03/2010 8:26 AM, Michael Friendly wrote:
In a function, say foo.glm for glm objects I want to use the name of the object as a label for some output, but *only* if a glm object was passed as an argument, not a call to glm() producing that object.
How can I distinguish these two cases?

Look at typeof(substitute(object)).  For example,

> f <- function(object) typeof(substitute(object))
> f(aname)
[1] "symbol"
> f(aname+1)
[1] "language"

That will tell you if an object was passed by name, or if you got an expression to produce the object.

One problem with this approach is that it only looks at the direct call to f, for example

> g <- function(x) f(x)
> g(aname + 1)
[1] "symbol"

because substitute looks at the f(x) call, not the g(aname + 1) call.

Duncan Murdoch



For example, I can use the following to get the name of the argument:

foo.glm <- function(object) {
    oname <- as.character(sys.call())[2]
    oname
}

 > indep <- glm(Freq ~ mental + ses, family = poisson, data = Mental)
 > foo.glm(indep)
[1] "indep"

But in foo.glm() I want to avoid using this as oname:
> foo.glm(glm(formula = Freq ~ mental + ses, family = poisson, data = Mental))
[1] "glm(formula = Freq ~ mental + ses, family = poisson, data = Mental)"

Here is Mental, if it matters.

 dput(Mental)
structure(list(ses = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 6L, 6L, 6L,
6L), .Label = c("1", "2", "3", "4", "5", "6"), class = c("ordered",
"factor")), mental = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L,
4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L,
4L), .Label = c("Well", "Mild", "Moderate", "Impaired"), class = c("ordered",
"factor")), Freq = c(64L, 94L, 58L, 46L, 57L, 94L, 54L, 40L,
57L, 105L, 65L, 60L, 72L, 141L, 77L, 94L, 36L, 97L, 54L, 78L,
21L, 71L, 54L, 71L)), .Names = c("ses", "mental", "Freq"), row.names = c(NA,
-24L), class = "data.frame")


______________________________________________
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