R Code to Add a Special Header When Exporting a Matrix to a Text File

155 views Asked by At

I have code that is creating a 141 x 131 matrix from one big column and exporting it as a text file. So far it works good. I am going to import these files into ArcGIS using the ASCII to raster tool. For ArcGIS to import them a five line header is required, with the data following the header like this:

NCOLS 131
NROWS 141
XLLCENTER -150
YLLCENTER -70
CELLSIZE 1
NODATA_VALUE -32768
265 41.7 1.8 12 16 18.3 16.5 18.3 19.7 24.5 26.1 28.4...

It is trivial to manually paste in this header once R saves the text file, but I have over 900 files I need to process so I'd like to have R add the header when it exports the text file. Is that possible or can I just add the header lines as the first 5 rows of the matrix and then export it?

Edit: this section below is regarding an additional question I asked in the comments.

Here is my whole code:

batch_tpose <- function(filename) {
dat <- matrix(scan(file = filename),ncol=3,byrow=T)
dat_trans <- matrix(dat[,3], 141, byrow=FALSE)

header <- "NCOLS 131
NROWS 141
XLLCENTER -150
YLLCENTER -70
CELLSIZE 1
NODATA_VALUE -32768"

writeLines(header, filename)
write.table(dat_trans, file = filename, row.names=FALSE, col.names=FALSE, append=TRUE)

## This works, I just need the output to be something like out/filename...


}

batch_tpose("200RelVort-nwatl-20201008-15.txt")

I want to be able to process a bunch of files in the batch_tpose command at the bottom using list.files. Right now I'm just testing with one file. This works but it writes the files to the working directory. It also overwrites the source file because it is in the same directory. How do I write the output files to the "out" directory? I've tried out/filename and file = out/filename but that creates a new file called "filename." I've tried other combinations but they caused errors.

1

There are 1 answers

8
tpetzoldt On BEST ANSWER

You can first write the header with readLines and then the data with write.table (or a similar function). The trick is then the option append = TRUE. Here an example:

header <- "NCOLS 131
NROWS 141
XLLCENTER -150
YLLCENTER -70
CELLSIZE 1
NODATA_VALUE -32768"

data <- matrix(rnorm(100), ncol=10)

writeLines(header, "file.txt")
write.table(data, file="file.txt", col.names=FALSE, row.names=FALSE, append=TRUE)

You can also paste the header text with usual R functions together:

ncols=131
nrows=141

header <- paste0("NCOLS ", ncols, 
"\nNROWS ", nrows,
"\nXLLCENTER -150
YLLCENTER -70
CELLSIZE 1
NODATA_VALUE -32768")

Line breaks can either be specified as line breaks within the text string or with the newline "\n" code.