3

我正在尝试将页码添加到使用 R 中的绘图生成并以 pdf 格式保存的 pdf 文件中。我正在使用其中d_pplydata.frameplot 命令。

我认为d_pply这会帮助我避免for循环。下面是来自我的原始数据的样本,其中包含更多因素。

data1 <- structure(list(fact = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L
), .Label = c("A", "B", "C"), class = "factor"), speed = c(10.56, 
11.94, 13.61, 15, 16.67, 18.06, 19.44, 20.28, 21.11, 21.67, 22.5, 
23.06, 23.61, 24.44, 25, 25.56, 26.11, 26.94, 27.5, 15.83, 16.67, 
17.5, 18.06, 18.89, 19.72, 20.56, 21.11, 21.94, 22.5, 23.33, 
23.89, 24.44, 25, 25.56, 26.11, 26.67, 27.22, 8.61, 10.28, 11.94, 
13.61, 15, 16.39, 17.5, 18.89, 19.72, 20.83, 21.67, 22.22, 22.5, 
23.06, 23.61, 23.89, 23.89, 23.61)), .Names = c("fact", "speed"
), class = "data.frame", row.names = c(NA, -55L))

我试图通过使用全局索引来完成任务。但我正在寻找一种有效的方法来做到这一点。这个对我帮助不大。

index1 <<- 0
plot_pg <- function(x)
{ index1 <<- index1+1
  plot(x$speed,main=paste0('pg# ',index1))
}

genplot <- function(df1,filename1)
{
  pdfNAME <- paste0(name1,'.pdf')
  pdf(pdfNAME)
    d_ply(df1,c('fact'),function(x) plot_pg(x))
  dev.off()
}
genplot(data1,'data1Plots')

更新

我应该在这里提一下,我会data.frame用多个变量来分割我的……类似的东西ddply(data,c('var1','var2'),function(x) MyplotFunc(x))

4

1 回答 1

4

我会这样做:

genplot <- function(df1,filename1){
  pdfNAME <- paste0(filename1,'.pdf')
  tmp <- split(df1,df1$fact)
  pdf(pdfNAME)
  for (i in seq_along(tmp)){
    plot(tmp[[i]][,'speed'],main = paste0("pg#",i))
  }
  dev.off()
}

The idea that for loops are inherently slow is a myth. The issue is that it can be easy to slip into bad coding techniques inside the for loop that makes the operations you're doing take a long time.

In this case, all you're doing in the for loop is plotting, so I doubt there will be much of a performance difference between this and using something like lapply. The things to watch out for are growing objects (i.e. appending) and modifying objects, since both will result in excessive copying.

于 2013-05-16T16:06:27.663 回答