我在尝试为使用 R 中的 plot 生成并保存为 pdf 格式的文件添加页码。我使用
我认为使用
d_pply
对 data.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))
我尝试使用全局索引来完成任务。但是我正在寻找一种更有效的方法来做这件事。这个链接并没有完全帮助到我。
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')
更新
这里需要提到的是,我将会按照不止一个变量来分割我的数据框
,类似于ddply(data,c('var1','var2'),function(x) MyplotFunc(x))
for
循环是否有效?无论如何,如果没有“apply”函数族,您将如何使用for
循环完成它。 - Stat-R