问题
I'm trying to use a construct such as "with" to allow easier (lazier ?) manipulation of an R6 object. Consider the following (minimal) example:
library(R6)
ToyClass<-R6Class(classname = "ToyClass",
public = list(
data=data.frame(x=c(1,2,3),y=c(4,5,6)),
color = "red",
symbol = 16,
initialize=function(mult){
self$data$x <- self$data * mult
}
)
)
foo <- ToyClass$new(2)
I can, obviously, plot the data in my object with
plot(foo$data$x,foo$data$y,col=foo$color,pch=foo$symbol)
However, being lazy (and since I have a lot of such objects to plot, so copy/paste/edit is time-consuming and prone to errors) I'd like to do
with(foo,
plot(data$x,data$y,col=color,pch=symbol)
)
Which does not work:
Error in plot(data$x, data$y, col = color, pch = symbol) :
could not find function "plot"
I understand why (foo behaves as an environment, in which plot() is not defined), but I cannot find a solution. How can I look for function names, I presume, in the global environment ?
回答1:
Why not just add a plot
method:
ToyClass2<-R6Class(classname = "ToyClass2",
public = list(
data=data.frame(x=c(1,2,3),y=c(4,5,6)),
color = "red",
symbol = 16,
plot = function() {
plot(self$data$x,self$data$y,col=self$color,pch=self$symbol)
},
initialize=function(mult){
self$data$x <- self$data * mult
}
)
)
foo2 <- ToyClass2$new(2)
plot(foo2)
If that's no good, another approach would be to set a parent environment as follows:
parent.env(foo) <- .GlobalEnv
with(foo, plot(data$x, data$y, col=color, pch=symbol))
parent.env(foo) <- emptyenv() # removes the parent environment
This can even be wrapped up in a function to get a more with
-like feel:
with_global <- function(object, task_expr) {
task_expr <- substitute(task_expr)
parent.env(object) <- current_env()
with(object, eval(task_expr))
}
with_global(foo, plot(data$x, data$y, col=color, pch=symbol))
来源:https://stackoverflow.com/questions/63027627/use-with-with-an-r6-object