如何在R中调用函数时抑制绘图的创建?

时间:2021-11-26 22:57:05

I am using a function in R (specifically limma::plotMDS) that produces a plot and also returns a useful value. I want to get the returned value without producing the plot. Is there an easy way to call the function but suppress the plot that it creates?

我在R(特别是limma :: plotMDS)中使用了一个函数,它生成一个绘图并返回一个有用的值。我想获得返回值而不生成绘图。是否有一种简单的方法来调用函数但是抑制它创建的图?

1 个解决方案

#1


3  

You can wrap the function call like this :

您可以像这样包装函数调用:

plotMDS.invisible <- function(...){
    ff <- tempfile()
    png(filename=ff)
    res <- plotMDS(...)
    dev.off()
    unlink(ff)
    res
}

An example of call :

电话的一个例子:

x <- matrix(rnorm(1000*6,sd=0.5),1000,6)
rownames(x) <- paste("Gene",1:1000)
x[1:50,4:6] <- x[1:50,4:6] + 2
# without labels, indexes of samples are plotted.
mds <- plotMDS.invisible(x,  col=c(rep("black",3), rep("red",3)) )

#1


3  

You can wrap the function call like this :

您可以像这样包装函数调用:

plotMDS.invisible <- function(...){
    ff <- tempfile()
    png(filename=ff)
    res <- plotMDS(...)
    dev.off()
    unlink(ff)
    res
}

An example of call :

电话的一个例子:

x <- matrix(rnorm(1000*6,sd=0.5),1000,6)
rownames(x) <- paste("Gene",1:1000)
x[1:50,4:6] <- x[1:50,4:6] + 2
# without labels, indexes of samples are plotted.
mds <- plotMDS.invisible(x,  col=c(rep("black",3), rep("red",3)) )