我会采取一种稍微不同的方法,这可能更容易理解:
temp = list.files(pattern="*.csv")
for (i in 1:length(temp))
{
tmp <- read.csv(temp[i], header=FALSE, skip =20)
colnames(tmp) <- c("Date","Unit","Temp")
# Now what do you want to do?
# For instance, use the file name as the name of a list element containing the data?
}
更新:
temp = list.files(pattern="*.csv")
stations <- vector("list", length(temp))
for (i in 1:length(temp)) {
tmp <- read.csv(temp[i], header=FALSE, skip =20)
colnames(tmp) <- c("Date","Unit","Temp")
stations[[i]] <- tmp
}
names(stations) <- temp # optional; could process file names too like using basename
station1 <- station[[1]] # etc station1 would be a data.frame
这第二部分也可以改进,具体取决于您计划如何使用数据以及有多少数据。一个很好的命令是 str(some object)。它将真正帮助您理解 R 的数据结构。
更新#2:
将单个数据框放入您的工作区将非常困难 - 比我更聪明的人可能知道一些技巧。既然你想绘制这些,我首先让名字更像你想要的:
names(stations) <- paste(basename(temp), 1:length(stations), sep = "_")
然后我将遍历上面创建的列表,如下所示,随时创建您的图:
for (i in 1:length(stations)) {
tmp <- stations[[i]]
# tmp is a data frame with columns Date, Unit, Temp
# plot your data using the plot commands you like to use, for example
p <- qplot(x = Date, y = Temp, data = tmp, geom = "smooth", main = names(stations)[i])
print(p)
# this is approx code, you'll have to play with it, and watch out for Dates
# I recommend the package lubridate if you have any troubles parsing the dates
# qplot is in package ggplot2
}
如果要将它们保存在文件中,请使用以下命令:
pdf("filename.pdf")
# then the plotting loop just above
dev.off()
将创建一个多页 pdf。祝你好运!