Not nearly as elegant as @Roland's example and I'm not sure why have different values - actually I do thx to the comment below (different file).
library(stringr)
library(plyr)
library(raster)
f <- readLines("totno2_200601.asc")
# how many lat/lon values
bins.lon <- as.numeric(str_match(f[3], "Longitudes *: *([0-9]+) bins")[2])
bins.lat <- as.numeric(str_match(f[4], "Latitudes *: *([0-9]+) bins")[2])
# number of characters that represent a value
num.width <- 4
# how many lines do we need to encode the longitude bins
bins.lon.lines <- as.integer(bins.lon / (80/num.width))
# where does the data start
curr.lat.line <- 5
curr.lat.bin <- 1
m <- matrix(nrow=bins.lat, ncol=bins.lon+1)
repeat {
# get current latitude
lat <- as.numeric(str_match(f[curr.lat.line], "lat=\ +([0-9\\.\\-]+)")[2])
# show progress - not necessary
cat(curr.lat.bin, lat); cat("\n")
# get the values for the longitudes at current latitude
vals <- paste(f[(curr.lat.line+1):(curr.lat.line+bins.lon.lines)], sep="", collapse="")
# split them by 4 and assign to the proper entry
m[curr.lat.bin, ] <- c(lat, as.numeric(laply(seq(1, nchar(vals), 4), function(i) substr(vals, i, i+3))))
curr.lat.bin <- curr.lat.bin + 1
curr.lat.line <- curr.lat.line + bins.lon.lines + 1
if (curr.lat.bin > bins.lat) { break }
}
m <- m[nrow(m):1, ]
plot(raster(m))
Since you added a requirement to have this be able to be used in a loop to read multiple files:
library(stringr)
library(plyr)
library(raster)
# this is the function-ized version
tomsToMatrix <- function(fname, verbose=FALSE) {
f <- readLines(fname)
bins.lon <- as.numeric(str_match(f[3], "Longitudes *: *([0-9]+) bins")[2])
bins.lat <- as.numeric(str_match(f[4], "Latitudes *: *([0-9]+) bins")[2])
num.width <- 4
bins.lon.lines <- as.integer(bins.lon / (80/num.width))
curr.lat.line <- 5
curr.lat.bin <- 1
m <- matrix(nrow=bins.lat, ncol=bins.lon+1)
repeat {
lat <- as.numeric(str_match(f[curr.lat.line], "lat=\ +([0-9\\.\\-]+)")[2])
if (verbose) { cat(curr.lat.bin, lat); cat("\n") }
vals <- paste(f[(curr.lat.line+1):(curr.lat.line+bins.lon.lines)], sep="", collapse="")
m[curr.lat.bin, ] <- c(lat, as.numeric(laply(seq(1, nchar(vals), 4), function(i) substr(vals, i, i+3))))
curr.lat.bin <- curr.lat.bin + 1
curr.lat.line <- curr.lat.line + bins.lon.lines + 1
if (curr.lat.bin > bins.lat) { break }
}
m <- m[nrow(m):1, ]
return(m)
}
setwd("/data/toms") # whatever the source directory is for **your** files
t.files <- list.files("/data/toms")
t.files
[1] "totno2_200504.asc" "totno2_200505.asc" "totno2_200506.asc"
dat <- lapply(t.files, tomsToMatrix)
str(dat)
List of 3
$ : num [1:720, 1:1441] 89.9 89.6 89.4 89.1 88.9 ...
$ : num [1:720, 1:1441] 89.9 89.6 89.4 89.1 88.9 ...
$ : num [1:720, 1:1441] 89.9 89.6 89.4 89.1 88.9 ...
If you need them as named entries, that should not be difficult to add.