Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a printed message into a character vector

Tags:

r

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" 
like image 381
Rich Scriven Avatar asked Jun 24 '14 21:06

Rich Scriven


People also ask

How do you create a character vector?

How to create a character vector in R? Use character() or c() functions to create a character vector. character() creates a vector with a specified length of all empty strings whereas c() creates a vector with the specified values, if all values are strings then it creates a character vector.

How do I convert a Dataframe to a character vector in R?

If we want to turn a dataframe row into a character vector then we can use as. character() method In R, we can construct a character vector by enclosing the vector values in double quotation marks, but if we want to create a character vector from data frame row values, we can use the as character function.

How do I convert an observation to a character in R?

To convert all columns of the data frame into the character we use apply() function with as. character parameter. The lapply() function applies the given function to the provided data frame.

How do you set a character vector in R?

There are different ways of assigning vectors. In R, this task can be performed using c() or using “:” or using seq() function. Generally, vectors in R are assigned using c() function. In R, to create a vector of consecutive values “:” operator is used.


1 Answers

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"
like image 188
MrFlick Avatar answered Sep 29 '22 15:09

MrFlick