我在一个文件夹中有一堆.gpx文件,我试图用readOGR读取它们,并为每个.gpx文件在内存中获取一个文件。这里有什么不起作用:
myfiles <- list.files(".", pattern = "*.gpx")
for (i in 1:length(myfiles)) {
temp.gpx <- readOGR(dsn = myfiles[i], layer="tracks")
temp.gpx
}
这样做是读取所有文件,然后将它们写入temp.gpx。我想要做的就是阅读它们并将其写入,例如temp1.gpx,temp2.gpx等。
不幸的是,我对R很陌生,我不知道怎么做。我尝试在线查找并找到了一些特定于非空间文件的解决方案,并以某种方式弄乱了这些文件。
有谁知道如何做到这一点?
谢谢!
答案 0 :(得分:0)
您可以使用assign()
使用其他变量生成变量名称:
myfiles <- list.files(".",pattern = "*.gpx")
for (i in 1:length(myfiles)) {
varName <- paste0("temp", i, ".gpx")
assign(varName, readOGR(dsn = myfiles[i], layer="tracks"))
}
这将为循环的每次迭代创建一个字符变量varName
,其值为temp1.gpx
,temp2.gpx
等:
## i <- 1
varName <- paste0("temp", i, ".gpx")
## [1] "temp1.gpx"
然后assign()
会将readOGR()
的结果分配给当前的temp*.gpx
变量。
答案 1 :(得分:0)
The use of assign
is in most cases a very poor choice. Although Stuart Allen answered your question correctly, your are most likely asking the wrong question.
What you are trying to do is a typical beginners mistake. With this approach you end up with several named objects that are difficult to manipulate because you need to refer to them by their names, making it hard to use the objects in a loop, for example.
Instead you probably should make a list with all your objects:
gpx <- lapply(myfiles,
function(f) { readOGR(dsn=f, layer="tracks") }
)
And take it from there.