【问题标题】:in R Return a logical if my function plots a graph如果我的函数绘制图表,则在 R 中返回逻辑
【发布时间】:2017-04-21 03:19:00
【问题描述】:

您好,我有一个名为 basic_plot() 的函数,如果变量 plot_function = TRUE,它将生成一个绘图,否则它返回 NULL。如下

plot_function = TRUE;

basic_plot = function() {
 if(plot_function) {
  par(mfrow = c(1,3))
  plot(1:10,1:10,type = "o")
  plot(10:1,1:10,type = "o")
  plot(1:10,rep(5,10),type = "o")
 } else {
  NULL;
 }
}
basic_plot();

应该生成一个带有填充一些线条的树面板的图。这个函数连同它所依赖的变量一起嵌入在其他一些代码中。我想知道的是,如果绘图已绘制,我如何判断 if() 语句?例如

if(is.null(basic_plot())) {
  print("I haven't drawn the plot yet")
} else {
  print("I have drawn the plot and want to do more stuff.")
}

上面的问题是,如果一个函数绘制一个图形,它被认为是空的。所以这永远不会知道我何时绘制情节,例如

plot_function = TRUE;
is.null(basic_plot())
[1] TRUE

plot_function = FALSE;
is.null(basic_plot())
[1] TRUE

真正的应用是在一个闪亮的应用程序中,但实际上认为这可能是一个通用的 R 查询。除了在 basic_plot() 函数中生成绘图之外,我无法返回任何内容(避免在绘制绘图后明显返回某些内容)。我希望 is.null() 有一个替代函数,比如这个函数有没有做某事?

干杯, C

【问题讨论】:

  • 了解人们为什么对这个问题投反对票会很有用?所以我可以从中学习

标签: r plot shiny


【解决方案1】:

在您的函数basic_plot 中,plot(1:10,rep(5,10),type = "o") 命令没有为函数分配任何内容,所以它仍然是NULL

例如,下面会将TRUE 分配给您的函数。

plot_function = TRUE;

basic_plot = function() {
if(plot_function) {
par(mfrow = c(1,3))
plot(1:10,1:10,type = "o")
plot(10:1,1:10,type = "o")
plot(1:10,rep(5,10),type = "o")
TRUE
} else {
NULL;
}
}
basic_plot();

为了将绘图存储为对象,使用recordPlot()

 myplot<-recordPlot()

【讨论】:

    【解决方案2】:

    简单的答案:在你的函数中返回 TRUE 或 FALSE:

    basic_plot = function() {
     if(plot_function) {
      par(mfrow = c(1,3))
      plot(1:10,1:10,type = "o")
      plot(10:1,1:10,type = "o")
      plot(1:10,rep(5,10),type = "o")
      return(TRUE) # Now the function will plot, then return TRUE
     } else {
      return(FALSE) # Now the function will return FALSE instead of NULL
     }
    }
    
    # We can make this a function too
    check_plot <- function() {
      if(basic_plot()) {
        print("I have drawn the plot and want to do more stuff.")
      } else {
        print("I haven't drawn the plot yet")
      }
    }
    
    # Now we can simply check:
    plot_function <- TRUE
    check_plot()
    
    plot_function <- FALSE
    check_plot()
    
    # Note: it is generally bad practice to use global variables like this!
    

    【讨论】:

    • 我知道我试图在最后一句中警告该建议的答案,但显然不够清楚。但这不是一个选项,我不能让函数返回除情节之外的任何内容。关于全局变量的道歉,我只是懒惰地试图创建一个可重现的例子。
    • 我想你正在寻找 recordPlot 然后,请参阅:stackoverflow.com/questions/29583849/…
    猜你喜欢
    • 2014-04-22
    • 2016-08-09
    • 2012-07-02
    • 1970-01-01
    • 2015-05-15
    • 2018-10-13
    • 1970-01-01
    • 1970-01-01
    • 2017-11-05
    相关资源
    最近更新 更多