从R中的底层C函数中抑制消息
在脚本中,我经常调用函数Rcplex(),它将“CPLEX环境打开”和“已关闭的CPLEX环境”打印到控制台.由于该函数被频繁调用,因此它经常打印,这非常烦人.有没有办法压制这个?我尝试了sink(),suppressWarnings / Messages或者invisible(catch.output()),但这些都没有.我继续检查Rcplex()的代码,并找到打印到控制台的位置. Rcplex()调用底层C函数(Rcplex.c).在
code of rcplex.c中,我找到了导致打印的命令:
REprintf("CPLEX environment openedn"); REprintf("Closed CPLEX environmentn"); 有没有办法从REprintf()捕获输出,以便它不会打印到R控制台?显然,一种方法是乱用Rcplex.c文件并删除相应的行.但是,这不是一个非常干净的解决方案,这就是为什么我要求另一种方法来捕获C函数的输出. 解决方法
您通常使用sink()和capture.output()时遇到问题,因为sink()不会重定向REprintf的输出,正如我们在
source code中对REprintf的注释中所看到的:
/* ========= * Printing: * ========= * * All printing in R is done via the functions Rprintf and REprintf * or their (v) versions Rvprintf and REvprintf. * These routines work exactly like (v)printf(3). Rprintf writes to * ``standard output''. It is redirected by the sink() function,* and is suitable for ordinary output. REprintf writes to * ``standard error'' and is useful for error messages and warnings. * It is not redirected by sink(). 但是,我们可以使用type =“message”来处理这个问题;来自help(“capture.output”):
首先,我使用您正在处理的相同行为创建一个C函数: #include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] NumericVector example_function(NumericVector x) { REprintf("CPLEX environment openedn"); REprintf("Closed CPLEX environmentn"); // As mentioned by Dirk Eddelbuettel in the comments,// Rcpp::Rcerr goes into the same REprintf() stream: Rcerr << "Some more stuffn"; return x; } 如果我通常从R调用它,我得到: example_function(42) CPLEX environment opened Closed CPLEX environment Some more stuff [1] 42 但是,我可以这样做: invisible(capture.output(example_function(42),type = "message")) [1] 42 虽然输出打印到控制台,但消息却没有. 警告 如果我没有提到上面引用的帮助文件中的警告,我会失职:
原因是这将消除实际错误的所有输出.考虑以下: > log("A") Error in log("A") : non-numeric argument to mathematical function > invisible(capture.output(log("A"),type = "message")) > 因此,您可能希望或不希望将捕获的输出发送到文本文件,以防您必须诊断出错的地方.例如: invisible(capture.output(log("A"),type = "message",file = "example.txt")) 然后我不必在控制台中看到消息,但如果我之后需要检查example.txt,那么消息就在那里: Error in log("A") : non-numeric argument to mathematical function (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |