[R] Prevent Printing Function's Environment
Martin Maechler
m@ech|er @end|ng |rom @t@t@m@th@ethz@ch
Tue Aug 14 10:58:45 CEST 2018
>>>>> Abs Spurdle
>>>>> on Tue, 14 Aug 2018 15:16:08 +1200 writes:
> Hi All
> When you print a function constructed within a function, R
> prints it's environment. For example:
> > myfunction = function ()
> + { f = function () NULL
> + attributes (f) = list (class="myfunction", myattribute=1)
> + f
> + }
> > myfunction.f = myfunction ()
> > myfunction.f
> function ()
> NULL
> <environment: 0x03fcbc30>
> attr(,"class")
> [1] "myfunction"
> attr(,"myattribute")
> [1] 1
> One way to prevent this is to set the function's environment to the global
> environment.
> But I was wondering if there's a way to stop R from printing the
> environment without changing the environment?
Probably, not the way you want, but if you need it e.g., for
didactical reasons, here's a way that may be didactically
relevant in it self:
> ls.str
function (pos = -1, name, envir, all.names = FALSE, pattern,
mode = "any")
{
if (missing(envir))
envir <- as.environment(pos)
nms <- ls(name, envir = envir, all.names = all.names, pattern = pattern)
r <- unlist(lapply(nms, function(n) exists(n, envir = envir,
mode = mode, inherits = FALSE)))
structure(nms[r], envir = envir, mode = mode, class = "ls_str")
}
<bytecode: 0xb222858>
<environment: namespace:utils>
so, I want to suppress the last two lines that are printed.
That's a piece of cake if you know capture.output() :
> P2 <- function(.) writeLines(head(capture.output(.), -2))
> P2(ls.str)
function (pos = -1, name, envir, all.names = FALSE, pattern,
mode = "any")
{
if (missing(envir))
envir <- as.environment(pos)
nms <- ls(name, envir = envir, all.names = all.names, pattern = pattern)
r <- unlist(lapply(nms, function(n) exists(n, envir = envir,
mode = mode, inherits = FALSE)))
structure(nms[r], envir = envir, mode = mode, class = "ls_str")
}
>
More information about the R-help
mailing list