【问题标题】:Adding page numbers in pdf file generated by R在 R 生成的 pdf 文件中添加页码
【发布时间】:2013-05-16 15:18:41
【问题描述】:

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

我认为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))

我尝试使用全局索引来完成任务。但我正在寻找一种有效的方法来做到这一点。 This one 并没有帮到我。

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))

【问题讨论】:

  • for 循环有什么问题?
  • 这里的示例数据只显示了两个因素,但我实际上有大约 480 个因素,而且未来可能还会增加。你认为for 循环会有效吗?无论如何,您将如何使用没有“应用”系列函数的for 循环来实现。

标签: r pdf plot


【解决方案1】:

我会这样做:

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()
}

for 循环固有缓慢的想法是一个神话。问题是,很容易在 for 循环中陷入糟糕的编码技术,从而使您正在执行的操作需要很长时间。

在这种情况下,您在 for 循环中所做的只是绘图,所以我怀疑这与使用 lapply 之类的东西之间会有很大的性能差异。需要注意的是增长对象(即追加)和修改对象,因为两者都会导致过度复制。

【讨论】:

  • 我使用d_pply 的另一个原因是我必须将data.frame 拆分为多个变量。但我无法让split 在这种情况下工作。有什么建议吗?
  • @Stat-R 阅读文档:“在 as.factor(f) 定义分组的意义上的'因素',或在这种情况下它们的交互用于分组。”
  • R 在我写tmp &lt;- split(df1,as.list(df1$fact,df1$fac2)) 时进入了无限循环,其中fac2 是第二个因素。你知道为什么吗? 'tmp
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-25
  • 2014-12-26
  • 2012-12-01
  • 1970-01-01
相关资源
最近更新 更多