【问题标题】:use R to remove header (6 lines) from .asc file (ESRI ascii grid) and export使用 R 从 .asc 文件(ESRI ascii 网格)中删除标题(6 行)并导出
【发布时间】:2014-05-21 09:38:19
【问题描述】:

我有超过 800 个 .asc 文件(ESRI ascii 网格),每个文件都有一个由 6 行组成的标题,然后是由空格分隔的栅格数据。这里以一个小文件为例。我使用 read.asciigrid(sp 包)阅读它。

new("SpatialGridDataFrame" , 数据 = 结构(list(mydata.asc = c(4, 4, 4, 4, 3, 4, 4, 4, 1, 1, 1, 1, 1, 4, 4, 4, 4, 3, 4 , 4, 4, 1, 1, 1, 1, 1, 4, 4, 4, 4, 3, 4, 4, 4, 1, 1, 1, 1, 1, 4, 4, 4, 4, 3, 4, 4, 4, 6, 1, 1, 1, 1, 4, 4, 4, 4, 3, 4, 4, 4, 6, 1, 1, 1, 1, 4, 4, 4, 4, 3, 4, 4, 4, 6, 1, 1, 1, 1, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 1, 1, 1, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 1, 1, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 1, 1, 1, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6)), .Names = "mydata.asc", row.names = c(NA, -143L), class= "data.frame") , grid = new("GridTopology" , cellcenter.offset = c(394984.42630274, 2671265.4912109) , 像元大小 = c(25, 25) , cells.dim = c(13L, 11L) ) , bbox = 结构 (c(394971.92630274, 2671252.9912109, 395296.92630274, 2671527.9912109), .Dim = c(2L, 2L), .Dimnames = list(NULL, c("min", "max"))) , proj4string = new("CRS" , projargs = NA_character_ ) )

这是使用文本编辑器查看文件时的样子。

这是我想做的步骤

1) 读入文件 2)删除前6行(标题) 3) 将文件另存为具有相同文件名但位于不同位置的 .asc 文件

当然,我想对 800 个文件执行此操作,但如果我能弄清楚如何对一个文件执行此操作,我应该能够编写一个函数来遍历所有文件。

感谢您的帮助。

-al

更新: 感谢@Luca Braglia,这是对我有用的最终代码。

设置工作目录

setwd("c:/temp/hdr/ascii")
newdir <- "c:/temp/hdr/ascii_no_hdr/"

files <- dir(pattern="*.asc")

for (my.file in files){
  i <- read.table(my.file,skip=6,sep="")
  write.table(i,file=paste(newdir,my.file,sep=""),sep="",row.names=FALSE,col.names=FALSE)
}

我不想要 col 和 row 的名称。一段非常简单有效的代码。

【问题讨论】:

  • read.asciigrid 是否采用skip 参数?如果是这样,在 read 语句中添加skip=6 将避免读取前六行。
  • 我没有在参数中看到跳过参数。
  • 呃,考虑用 raster() 读取它们,生成合理的格式并将这些可怕的文本文件交给熔炉。您真的需要更多简化的文件吗?目标是什么?

标签: r ascii esri


【解决方案1】:

您可以列出所有文件,在 for 循环中读取所有文件(使用 read.tableskip 选项)

## you are in the directory with your asc files
files <- dir(pattern="*.asc")

# loop
for (my.file in  files) {
     i <- read.table(my.file, skip = 6, sep = " ")
     # change names here if you don't want V1, V2 ...
     write.table(i, file = paste("new_dir", my.file, sep = "/"), 
                 sep = " ", row.names = FALSE)

}   

【讨论】:

  • 这个答案没有解决如何删除每个 asc 文件的前 6 行,然后将它们全部保存为 asc 文件。
  • writeLines(readLines(srcfile)[-(1:6)], tgtfile) 将从解析列中保存
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-17
  • 2012-12-18
  • 1970-01-01
  • 2013-08-06
  • 1970-01-01
相关资源
最近更新 更多