假设我有一个文件"data.txt",可以使用以下代码创建
m <- matrix(c(13, 14, 4950, 20, 50, 4949, 22, 98, 4948,
30, 58, 4947, 43, 48, 4946), 5, byrow = TRUE)
write.table(m, "data.txt", row.names = FALSE, col.names = FALSE)
Run Code Online (Sandbox Code Playgroud)
将文件读入R scan,消息随数据一起传送.
( s <- scan("data.txt") )
# Read 15 items
# [1] 13 14 4950 20 50 4949 22 98 4948
# [10] 30 58 4947 43 48 4946
Run Code Online (Sandbox Code Playgroud)
我想将消息检索Read 15 items为字符向量.我知道我可以通过键入获得最后记录的警告last.warning,并可以将其转换为字符向量names(last.warning),但没有这样的对象last.message.
有没有办法将输出的消息转换为字符向量?期望的结果是
[1] "Read 15 items"
Run Code Online (Sandbox Code Playgroud) 使用options(show.error.locations = TRUE)处理异常时,显示错误位置似乎不起作用tryCatch.我试图显示错误的位置,但我不知道如何:
options(show.error.locations = TRUE)
tryCatch({
some_function(...)
}, error = function (e, f, g) {
e <<- e
cat("ERROR: ", e$message, "\nin ")
print(e$call)
})
Run Code Online (Sandbox Code Playgroud)
如果我然后查看变量e,那么位置似乎不存在:
> str(e)
List of 2
$ message: chr "missing value where TRUE/FALSE needed"
$ call : language if (index_smooth == "INDEX") { rescale <- 100/meanMSI[plotbaseyear] ...
- attr(*, "class")= chr [1:3] "simpleError" "error" "condition"
Run Code Online (Sandbox Code Playgroud)
如果我没有捕获错误,它将与源文件和行号一起打印在控制台上.如何使用tryCatch?
如何将某些代码的输出汇入变量?我希望该输出仍然进入控制台.
我更喜欢这种sink符号; 我不想使用capture.output有两个原因:
我想出了下面的代码,但它有点复杂.有更简单的解决方案吗?
fileName <- tempfile()
sink(fileName, split = TRUE)
...
sink()
out <- readChar(fileName, file.info(fileName)$size)
unlink(fileName)
Run Code Online (Sandbox Code Playgroud) RI希望将控制台命令存储到变量中.我已经尝试过以下链接中提出的解决方案,但没有运气:在R中,是否可以将控制台输出重定向到变量? 这是你正在使用的命令:
test <- capture.output(system("pa11y scuolafalconeborsellino.it;
perl -e \"print unpack('c', pack('C', $?)), \\$/\""), file = NULL)
Run Code Online (Sandbox Code Playgroud)
控制台中可见的输出是:
[4m [36m欢迎来到Pa11y [39m [24m [90m]我们现在为您嗅探您的页面.[39m [36m] [39mL加载页面... [36m> [39m运行HTML CodeSniffer ... [36m> [39m [31mError:HTML CodeSniffer error [39m]
-1
但是变量测试是空的.
谢谢!
我正在尝试从打印输出不打印到控制台的功能输出.
capture.output在某些答案中建议使用该功能,但我不清楚如何捕获输出但仍然返回函数的输出.
例如,如果我有功能f()并且想要"printed output!"不打印到控制台但是"value"要返回:
f <- function() {
print("printed output!")
return("value")
}
# printed output is returned - want to capture the output
f()
#> [1] "printed output!"
#> [1] "value"
# also doesn't work, as captured output and function's output is returned
capture.output(f())
#> [1] "[1] \"printed output!\"" "[1] \"value\""
Run Code Online (Sandbox Code Playgroud)
我认为解决方案可能涉及使用sink(和con()),但使用它们的答案不使用函数(因此我在应用该方法时遇到困难).