假设我有一个文件"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)
默认的hander message()
将结果发送到stderr
via cat()
.你可以捕获它
tc <- textConnection("messages","w")
sink(tc, type="message")
s <- scan("data.txt")
sink(NULL, type="message")
close(tc)
messages
# [1] "Read 5 items"
Run Code Online (Sandbox Code Playgroud)