2017-04-21 97 views
0

嗨我有一个函数称为basic_plot(),如果变量plot_function = TRUE将生成一个绘图,否则它返回一个NULL。它如下所示在R返回一个逻辑,如果我的函数绘制一个图

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.") 
} 

上面的问题是,如果函数绘制一个图,它被认为是null。所以这永远都不会知道,当我画的情节e.g

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

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

这样做的真正应用是在一个闪亮的应用程序,但实际上认为这可能是一个通用[R查询。除了在basic_plot()函数中生成绘图外,我不能返回任何东西(避免在绘制绘图之后显然返回某些东西)。我希望有一个替代函数为is.null(),例如该函数是否执行某些操作?

干杯, Ç

+0

这将是有益的知道为什么人们失望投票这个问题?所以我可以从这里学到 –

回答

1

在你的函数basic_plotplot(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() 
1

答案很简单:返回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! 
+0

我知道这个答案,我试图在最后一句中提出这个建议,但显然还不够清楚。但这不是一个选项,我不能让该函数返回除情节以外的任何内容。关于全局变量的道歉我只是懒得试图创建一个可重复的例子。 –

+1

我想你正在寻找'recordPlot'然后,请参阅:http://stackoverflow.com/questions/29583849/r-saving-a-plot-in-an-object –

相关问题