Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

r - Convert a printed message into a character vector

Suppose I have a file "data.txt", which can be created with the following code

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)

Reading the file into R with scan, a message is delivered along with the data.

( s <- scan("data.txt") )
# Read 15 items
#  [1]   13   14 4950   20   50 4949   22   98 4948
# [10]   30   58 4947   43   48 4946

I'd like to retrieve the message Read 15 items as a character vector. I know I can get the last recorded warning by typing last.warning, and can turn it into a character vector with names(last.warning), but there is no such object as last.message.

Is there a way to convert an outputted message to a character vector? The desired result would be

[1] "Read 15 items" 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The default hander for message() sends the result to stderr via cat(). You can capture that with

tc <- textConnection("messages","w")
sink(tc, type="message")
s <- scan("data.txt")
sink(NULL, type="message")
close(tc)

messages
# [1] "Read 5 items"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...