Mark
Mark

Reputation: 108557

Write Plot Text/Binary into Variable

Is there a way to have an R Device (postscript would be great) write the output into a variable instead of a file?

For example I know this:

postscript(file="|cat")
plot(1:10)
dev.off()

Will send the postscript text to STDOUT. How can I get that text into a variable within R?

Upvotes: 2

Views: 2196

Answers (4)

stotastic
stotastic

Reputation: 796

I've had success in getting the Binary of a plot into an R variable as a string. Its got some read/write overhead. In the snippet below, R saves the plot as a temp file and reads it back in.

## create a plot
x <- rnorm(100,0,1)
hist(x, col="light blue")

## save plot as temp file
png(filename="temp.png", width=500, height=500)
print(p)
dev.off()

## read temp file as a binary string
plot_binary <- paste(readBin("temp.png", what="raw", n=1e6), collapse="")

Maybe this is helpful to you.

Upvotes: 3

hadley
hadley

Reputation: 103928

You should be able to use a textConnection as follows.

tc <- textConnection("string", "w")

postscript(tc)
plot(1:10)
dev.off()

But string remains blank - maybe a bug?

Upvotes: 0

Harlan
Harlan

Reputation: 19401

Why on earth would you want to do that? R is not a very good system for manipulating Postscript files. If nothing else, you can use tempfile() to write the image to a file, which you can then read in using standard file functions. If you wanted to be fancy, you could perhaps use fifo() pipes, but I doubt it'll be much faster. But I suspect you'd be better off with a different approach.

Upvotes: 1

Jeff
Jeff

Reputation: 1426

postscript takes a command argument, hence postscript(file="",command="|cat")

Upvotes: 1

Related Questions