我有多个CSV作为输入,基本上有lat长信息,我正在导出.tiff图像,这些图像在地图上绘制了这些lat长度。我想知道如何循环这个过程,以便我可以读取多个CSV,从而生成对应于这些CSV的多个地图(.tiff)。任何帮助将不胜感激!!
以下是我目前使用的代码
rm(list=ls())
sclusters_1 <- readLines("C:\\Users\\D85_H.csv")
skip_second <- sclusters_1[-2]
sclusters <- read.csv(textConnection(skip_second), header = TRUE)
library(grDevices)
library(PBSmapping)
library(maptools)
library(sp)
myShapeFile<-importShapefile("C:\\Users\\st99_d00_shp\\st99_d00",readDBF=TRUE, projection = "LL")
ConvUS <- convUL(myShapeFile)
addressEvents<-as.PolyData(sclusters,projection="LL", zone = 15)
uaddressEvents <- convUL(addressEvents)
sclusters_cl <- unique(sclusters$PID)
len <- length(sclusters_cl)
palette(c("dodgerblue3","red3","olivedrab","purple4","turquoise2","orange3","lightskyblue4","mediumorchid3","saddlebrown","skyblue4"))
setwd("C:/Users/")
name, leave .tiff extension
tiff(filename = "Test.tiff",
width = 3750, height = 3142, units = "px", pointsize = 12,
compression = "lzw",
bg = "transparent")
plotMap(ConvUS , xlim=c(-8000,3500), ylim=c(2000,9500), plt=c(0.07,0.97,0.07,0.98), bg = "white", border = "darkgrey", axes=FALSE, xlab=" ",ylab=" ", lty = 1, lwd = 2)
addPoints(uaddressEvents,col=1:len,cex=2.5, pch = "O")
legend("topright",legend = sclusters_cl, cex=0.7, fill=palette())
#close output file stream
dev.off()
答案 0 :(得分:0)
请注意,这是未经测试的:
由于导入和导出文件名都是作为长度为1的字符向量传递的,因此您可以创建类似m <- matrix(c("infile1.csv", "outfile1.tiff", "infile2.csv", "outfile2.tiff"),nrow=2)
的矩阵。
然后你可以将整个事物包裹在该矩阵的列上的for
循环中,例如: for(j in 1:ncol(m))
。然后,将"C:\\Users\\st99_d00_shp\\st99_d00"
替换为m[1,j]
,将"Test.tiff"
替换为m[2,j]
。
更好的做法可能是将整个事物包装在函数中,然后编写一个只调用该函数的单独循环。例如:
myTIFF <- function (infile, outfile) {
# stuff you want to do to each pair of input and output files
}
m <- matrix(c(
"infile1.csv", "outfile1.tiff",
"infile2.csv", "outfile2.tiff"
# and so on
), nrow = 2)
for(j in 1:ncol(m)) myTIFF(m[1, j], m[2, j])
另请注意,R具有名为dir
的函数,该函数以ls
为当前环境中的变量执行的方式自动提取目录的内容作为字符向量。如果您有大量CSV文件,则可以使用此文件(可能与grep
一起使用)以编程方式生成矩阵m
,而不是手动输入。