简体   繁体   中英

Is there a way to get R print ouput as string?

Is there a simple way to get the output of print as a string variable? Something like:

output_string = print(object)

the function print() imho has a rather "intelligent" way of representing objects respectively object information as strings. Hence it would be useful to be able to process this output.

I thought all print() does is calling the toString() method on the object it is called with. However doing toString(object) gives different results and I'd like to get the string that print(object) generates... just not as output to the console but stored in a variable.


My context: I create a random forest model. Doing print(rf) gives me some basic stats about the model, that I'd like to write to a log file, whereas toString(rf) gives me a huge string with what seems to be an actual string representation of the full tree (splits etc). So I'd like to do:

rf = randomForest(...)
fileConn = file("rf.log")
writeLines(c(">>> random forest:", print(rf) ), fileConn)
close(fileConn)

I tried to get some information about this from the docs , but this doesn't seem to be an advertised feature. There is something about invisible(rf) , I was hoping this would do what I want, but it merely seems to copy the object.

I think this may be what you are after ?

# As vector:
res_vec <- capture.output(
  print(df)
)

cat(res_vec)

# As scalar:
res_scalar <- paste0(capture.output(
  print(df)
), collapse = "\n")

cat(res_scalar)

Data:

df <- data.frame(Mason_Id = sample(c("Mason1", "Mason2","Mason3","Mason4","Mason5","Mason6"), 12, T),
Registration_Date = c("01-08-2020", "01-08-2020","05-08-2020","07-08-2020",
"02-09-2020", "02-09-2020","02-09-2020",
"03-09-2020","04-09-2020","01-10-2020","02-10-2020",
"06-10-2020"), Token_Count = runif(12, 10, 100), stringsAsFactors = FALSE)

You could also have a look at the sink() function as it captures all the output into a text file that is normally shown in the console.

From ?sink :

sink("sink-examp.txt")
i <- 1:10
outer(i, i, "*")
sink()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM