【问题标题】:Plotting inside a function passed to ddply在传递给 ddply 的函数内绘图
【发布时间】:2016-03-09 01:15:51
【问题描述】:

我正在使用 ddply 对大型数据框进行数十次计算密集型分析。数据框由每个受试者的序列数据(第 1 行 = 试验 1,第 2 行 = 试验 2 等)组成,每个受试者有几个试验块。分析返回几个我绑定并返回的数值度量,但它也返回数据的稀疏矩阵表示,我想将其绘制到文件中。

data <- read.table("data.tsv", header= TRUE)

fqra <- function(x) {
   temp <- crqa(as.numeric(x$to.roi), as.numeric(x$to.roi), delay = 1, embed = 1,
   rescale = 0, radius = .001, normalize=0,mindiagline = 2, minvertline = 2, 
   tw=0, whiteline = FALSE, recpt=FALSE, side="upper", 
   checkl = list(do = FALSE, thrshd = 3, datatype = "categorical", 
   pad = FALSE))

   directory = "~/TS14data/Plots/"
   a = paste(directory, as.character(x$sid[1]), as.character(x$game.num[1]), ".png",sep="_")
   png(filename = a)
   b<- image(temp$RP)
   dev.off()

   return(cbind(temp$RR, temp$DET, temp$NRLINE, temp$maxL, 
temp$L, temp$ENTR, temp$rENTR, temp$LAM, temp$TT))
}

results <- ddply(Eyedatdata, .(subject, block), fqra)

代码运行没有错误,并按主题和块为我提供了没有问题的结果,但是找不到这些图。这是 plyr 运作方式的问题吗?我不能在 ddply 的函数中打开设备吗?

编辑:一个更简单的例子重现了这个问题。我有一个稀疏矩阵,我想创建它的图像并将其放入文件中。

library(matrix)
f<-function(x) {

    T2 <- new("dgTMatrix", i = as.integer(c(1,1,0,3,3)), j = as.integer(c(2,2,4,0,0)), x=10*1:5, Dim=4:5)
    png("example.png"); 
    image(T2)
    dev.off() 
}

results<-ddply(mtcars, .(gear), f)

删除函数内的所有内容并独立运行它会生成“example.png”图。似乎正在发生的是 image(T2) 不会从 ddply 调用中输出到文件。我不知道为什么会发生这种情况。

【问题讨论】:

  • 如果您使用示例输入数据制作更多 reproducible example 以消除与您的问题无关的复杂性,这将有所帮助。这个简单的例子对我有用:f&lt;-function(x) {png(paste0("gear-",x$gear[1],".png")); plot(drat~qsec, x);dev.off();x}; results&lt;-.ddply(mtcars, .(gear), f)(文件在工作目录中生成)。这让我相信可以打开设备并在 plyr 调用中写入。
  • 通过将上面的代码更改为绘图(temp$RP)而不是图像(temp$RP),这确实会生成带有绘图的 .png 文件。但是,plot() 不能正确地表示这些数据,这就是我使用 image() 的原因。所以现在看来​​问题是从 image() 函数生成的图没有进入设备,这很令人困惑。我正在研究一个可重现的例子。应该很快完成。
  • 将其更改为print(image(T2))。 Matrix 库(您显然正在使用)覆盖默认基本 image() 函数以返回需要显式 print()ed 的 trellis 对象
  • 做到了。谢谢!

标签: r plot plyr


【解决方案1】:

MrFlick 在上面的 cmets 中回答了这个问题。

【讨论】:

  • 随意把你最终使用的解决方案放在这里,然后接受答案。
猜你喜欢
  • 1970-01-01
  • 2014-03-23
  • 1970-01-01
  • 2016-08-13
  • 2019-01-31
  • 1970-01-01
  • 2014-01-31
  • 2017-04-03
  • 1970-01-01
相关资源
最近更新 更多