我是R的新手,似乎很难创建一个for循环来创建一个包含6个图表(2列x 3行)的PDF图形表。我使用以下循环将CSV导入单独的数据帧。
##create filenames object that lists the csv files in a folder
filenames <- list.files(path="C:/Survey_Stage/Data_Transfer/Survey_Stage/Stage_Discharge_Relations/CIDA/", pattern="*.csv")
##run loop that imports each csv file in the folder, creates a dataframe, assigns the filename to the dataframe, and adds column names
for(i in filenames)
{
filepath <-file.path("C:/Survey_Stage/Data_Transfer/Survey_Stage/Stage_Discharge_Relations/CIDA/", paste(i, sep=","))
assign(i, read.table(filepath, header = TRUE, sep = ",")[,c('SP_elev', 'flow')])
}
在我的项目中,我总共有23个csv,并且想要制作6张图形表。
下面是csv导入循环中生成的数据框的示例。
> Z041R.csv
SP_elev flow
1 840.5466 5430
2 840.9774 8285
3 841.1020 9162
4 841.2236 10175
5 842.4053 18450
6 840.7600 6780
7 840.9493 8110
8 841.6590 12700
9 842.6615 20200
10 841.2138 10175
11 845.0801 41977
12 841.4786 11431
13 841.6829 13000
14 845.1645 42500
15 841.6142 12400
16 841.2574 10200
17 842.2315 16400
18 840.9390 8040
I flow是自变量,SP_elev是因变量。我已经想出了如何单独创建grahic表,但是真的想要一个for循环来自动化这个过程。有什么想法吗?
这是我试过的循环。
##run loop to plot the csv files
pdf(file="myplots.pdf",paper="letter")
par(mfrow=c(3,2))
for(i in filenames)
{
plot (data.frame(i[flow], i[elevation]), xlab=expression(paste("Discharge (", ft^3, "/s)",sep = "")), ylab= "Elevation (m)", main = i)
}
dev.off()
谢谢,
Dubbdan
答案 0 :(得分:0)
我认为你需要这样的东西。假设每个csv文件恰好有2列。否则,从变量“crtdata。
中提取所需的列pdf(file="myplots.pdf",paper="letter")
for(i in filenames)
{
crtdata = read.csv(i)
plot (crtdata, xlab=expression(paste("Discharge (", ft^3, "/s)",sep = "")), ylab= "Elevation (m)", main = i)
}
dev.off()
答案 1 :(得分:0)
这只是@BigFinger解决方案的一个小调整(带注释):
# read in list of filenames
filenames <- list.files(path="C:/Survey_Stage/Data_Transfer/Survey_Stage/Stage_Discharge_Relations/CIDA/", pattern="*.csv")
# open the PDF device
pdf(file="myplots.pdf", paper="letter")
# loop through the filenames
for(i in filenames) {
# build the path to the current file
filepath <- file.path("C:/Survey_Stage/Data_Transfer/Survey_Stage/Stage_Discharge_Relations/CIDA", paste(i))
# read in the data frame
dat <- read.csv(filepath)
# plot the chart using column names just incase they aren't all in the same exact format
plot (dat[,c('SP_elev', 'flow')], xlab=expression(paste("Discharge (", ft^3, "/s)",sep = "")), ylab= "Elevation (m)", main = i)
}
# close the PDF device
dev.off()
如果您不想在地块标题中使用main = gsub(".csv", "", i, fixed=TRUE)
,则可以在plot
来电中执行.csv
。