Writing Text / Binary Code to Variable

Is there a way for the device R

(postscript would be great) to write the output to a variable instead of a file?

For example, I know this:

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

      

Sends postscript text to STDOUT

. How can I get this text in a variable inside R

?

+2


source to share


4 answers


I have had success in getting the plot binary into an R variable as a string. Its got some read / write overhead. In the snippet below, R saves the graph as a temporary file and reads it back.

## 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="")

      



It might be helpful for you.

+3


source


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



+1


source


Why would you do this? R is not a very good system for handling Postscript files. If nothing else, you can use tempfile () to write the image to a file, which can then be read using standard file functions. If you want to be fancy you can use fifo () pipes, but I doubt it will be much faster. But I suspect you will be better off with a different approach.

+1


source


You should be able to use a textual connection like this.

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

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

      

But it string

remains empty - maybe a mistake?

0


source







All Articles