有没有办法让 R 设备(postscript会很棒)将输出写入变量而不是文件?

例如,我知道:

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

将postscript文本发送到 STDOUT 。如何将该文本转换为 R 中的变量?

有帮助吗?

解决方案

我已成功将一个情节的二进制作为一个字符串变成一个R变量。它有一些读/写开销。在下面的代码片段中,R将绘图保存为临时文件并将其读回。

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

也许这对你有帮助。

其他提示

postscript采用命令参数,因此postscript(file =&quot;&quot;,command =&quot; | cat&quot;)

为什么你想要这样做呢? R不是一个非常好的操作Postscript文件的系统。如果不出意外,您可以使用tempfile()将图像写入文件,然后可以使用标准文件函数读取该文件。如果你想要花哨,你可以使用fifo()管道,但我怀疑它会更快。但我怀疑你会采用不同的方法做得更好。

您应该能够使用textConnection,如下所示。

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

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

但是 string 仍然是空白的 - 也许是一个错误?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top