Question

I have over 800 .asc files (ESRI ascii grids) that each have a header consisting of 6 lines, then the raster data separated by spaces. Here is a small file as an example. I read it in using read.asciigrid (sp package).

new("SpatialGridDataFrame" , data = structure(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" , cellcentre.offset = c(394984.42630274, 2671265.4912109) , cellsize = c(25, 25) , cells.dim = c(13L, 11L) ) , bbox = structure(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_ ) )

Here is what the file looks like if you view it with a text editor.

enter image description here

Here are the steps I would like to do

1) read in file 2) remove first 6 lines (header) 3) save file back out as .asc file with the same filename but in a different location

Of course, I'd like to do this to 800 files, but if I can figure out how to do this for one file, I should be able to write a function to loop through all files.

Thanks for any help.

-al

UPDATE: This is the final code that worked for me, thanks to @Luca Braglia.

Set working directory

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)
}

I didn't want the col and row names. A very simple and effective piece of code.

Was it helpful?

Solution

You can list all files, within a for loop read them all (using skip option of read.table)

## 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)

}   
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top