我正在尝试使用for循环遍历多个标头,以便创建多个图。当我将头变量传递给for循环时,我只是不确定我做错了什么,因为我不断从R获得警告和错误。
这是我正在使用的for循环:
dflist <- c('ABStemp', 'ABSelec', 'ABSheat')
for (i in dflist) {
plot1<-contourplot(i ~ hour * weekday | month,
data = HourlyTotal,
cuts = 200,
labels=TRUE,
contour=FALSE,
drop.unused.levels = lattice.getOption("drop.unused.levels"),
region = TRUE,
pretty=FALSE,
xlab = "",
ylab = "Day of Week",
col.regions=colorRampPalette(c("blue","yellow","red")),
main = "Absolute Error (Temperature)",
layout=c(2,4),
as.table= TRUE)
plot2<-contourplot(i ~ hour * weekday,
aspect=0.3,
data = HourlyTotal,
cuts = 200,
#labels=TRUE,
contour=FALSE,
region = TRUE,
pretty=FALSE,
xlab = "Hour of Day",
ylab = "Day of Week",
col.regions=colorRampPalette(c("blue","yellow","red"))
)
plot3<-contourplot(i ~ hour * month,
aspect=0.3,
data = HourlyTotal,
cuts = 200,
#labels=TRUE,
contour=FALSE,
region = TRUE,
pretty=FALSE,
xlab = "Hour of Day",
ylab = "Month of Year",
col.regions=colorRampPalette(c("blue","yellow","red"))
)
pdf(paste('Rplot',i,'.pdf'), width=8, height=12)
print(plot1, more=TRUE)
print(plot2, more=TRUE)
print(plot3, more=FALSE)
dev.off()
}
我在上面尝试了很多变化,但每次,i变量都无法正确传递到循环中,并且我在每个格子图中得到NA。
我正在使用的数据集可以在这里找到:SummaryData。此外,我的完整代码可在线获取:http://danielcoakley.com/projects/energy-simulation/
谢谢!
答案 0 :(得分:1)
您可以构建表示公式的字符串,然后使用formula
函数创建as.formula
对象。
as.formula(paste(i, "~ hour * weekday | month"))
答案 1 :(得分:1)
感谢@ zero323上面的解决方案,以下代码现在可以正常运行。
dflist <- c('ABStemp', 'ABSelec')
for (i in dflist) {
plot1<-contourplot(as.formula(paste(i, "~ hour * weekday | month")),
data = HourlyTotal,
cuts = 200,
labels=TRUE,
contour=FALSE,
drop.unused.levels = lattice.getOption("drop.unused.levels"),
region = TRUE,
pretty=FALSE,
xlab = "",
ylab = "Day of Week",
col.regions=colorRampPalette(c("blue","yellow","red")),
main = "Absolute Error (Temperature)",
layout=c(2,4),
as.table= TRUE)
plot2<-contourplot(as.formula(paste(i, "~ hour * weekday")),
aspect=0.3,
data = HourlyTotal,
cuts = 200,
#labels=TRUE,
contour=FALSE,
region = TRUE,
pretty=FALSE,
xlab = "Hour of Day",
ylab = "Day of Week",
col.regions=colorRampPalette(c("blue","yellow","red"))
)
plot3<-contourplot(as.formula(paste(i, "~ hour * month")),
aspect=0.3,
data = HourlyTotal,
cuts = 200,
#labels=TRUE,
contour=FALSE,
region = TRUE,
pretty=FALSE,
xlab = "Hour of Day",
ylab = "Month of Year",
col.regions=colorRampPalette(c("blue","yellow","red"))
)
plot4<-contourplot(as.formula(paste(i, "~ Meas.DryBlb * hour")),
aspect=1,
contour=FALSE,
region = TRUE,
data = HourlyTotal,
)
png(paste('Model\\Current Model\\Results\\',i,'.png'), width = 3600, height = 5000, units = "px", res = 400)
print(plot1, position = c(0,.5,1,1), more=TRUE)
print(plot2, position = c(0,.25,1,.5), more=TRUE)
print(plot3, position = c(0,0,1,.25), more=FALSE)
dev.off()
}
答案 2 :(得分:0)
问题是字符串"ABStemp"
未被解释为数据框中的名称。除了as.formula()
解决方案之外,您还可以尝试字符串引用正常的上下文。
将i
的{{1}}替换为contourplot
HourlyTotal[,i]
。这适用于ggplot
。对Lattice不确定。