编辑:添加完整代码
我为“情节”做了一个S4方法似乎正在工作,除了它向控制台输出一些迷路NULL
,我无法弄清楚它来自哪里。这是顶级代码:
print(plot(x = flux, y = 1, fastplot = TRUE, quietly = TRUE))
上课:
flux <- setClass(
# Set the class name
"flux",
slots = c(
raw.data = "list",
source.files = "character",
data = "matrix",
time = "POSIXct",
datatype = "character",
metadata = "data.frame"
)
)
方法:
setMethod("plot",
signature(x = "flux"),
function (x, y, ...) {
CheckFluxObject(x)
params <- LoadDefaults(flux = x)
# Interpret 'plot' arguments
par.restore <- par(no.readonly = TRUE)
on.exit(expr = par(par.restore), add = TRUE)
arguments <- list(...)
if (!("fastplot" %in% names(arguments))) {
fastplot <- FALSE
} else {
fastplot <- arguments$fastplot
arguments$fastplot <- NULL
}
if (!("quietly" %in% names(arguments))) {
quietly <- FALSE
} else {
quietly <- arguments$quietly
arguments$quietly <- NULL
}
par(ask=!(fastplot))
if (!("ylab" %in% arguments)) {
ylab <- params["units"]
} else {
ylab <- arguments$ylab
arguments$ylab <- NULL
}
# Pull relevant 'flux' class object data
data <- slot(x, "data")
if (missing("y")) {
y <- 1:ncol(data)
} else {
stopifnot(
is.integer(y),
all(y %in% 1:ncol(data))
)
}
# Bulk function execution
if (quietly == FALSE) {
message("Plotting data traces:")
}
plot.obj <- plot.new()
print("NULL is in the 'for' loop...")
for (i in y){
main <- colnames(data)[i]
plot.obj <- plot(slot(x, "time"), data[, i], main = main,
xlab = "Time", ylab = ylab, unlist(arguments))
print(plot.obj)
}
print("but is it also here??")
# Clean-up and exit
if (quietly == FALSE) {
message("Done plotting.")
}
if (length(y) == 1) {
invisible(plot.obj)
}
print("or here??")
invisible(NULL)
}
)
输出是:
[1] "NULL is in the 'for' loop..."
NULL
[1] "but is it also here??"
[1] "or here??"
NULL
如果我在print("what about here??")
之后再投掷invisible(NULL)
,
然后就是这样:
[1] "NULL is in the 'for' loop..."
NULL
[1] "but is it also here??"
[1] "or here??"
[1] "what about here??"
[1] "what about here??"
我有没有预料到函数返回或打印命令的某些行为? CheckFluxObject函数只是检查以确保所有插槽都已填满。
答案 0 :(得分:1)
如果有的话,我会把这个留在这里直到更好的答案出现:
显然,绘图对象的print
方法会返回NULL
,如果您尝试在函数中生成绘图,那么最好的方法就是使用{{ 1}}或invisible(plot.object)
,不是invisible(plot(x, y, ...))
。
我还不确定第二个NULL来自哪里......
编辑:找到第二个!就像方法本身中的print
一样,顶级代码中的print(plot.obj)
会抛出print
。删除所有NULL
命令会杀死所有鬼魂。