R and the Geostatistical Software Library data format

June 9, 2011

(This article was first published on Bart Rogiers - Sreigor, and kindly contributed to R-bloggers)

The *.gslib file format originates from the Geostatistical Software Library, but is also used in the follow-up of that software, i.e. the Stanford Geostatistical Modelling Software (SGeMS). Since not all geostatistical algorithms are implemented in R yet (especially the multiple-point ones), it is useful to have these functions for interacting with SGeMS. I also used it for 3D visualisation of geological datasets that I produced with R.
I extended some code that can be found here for writing *.gslib files from an R dataframe, with an added variable to enable a numeric no data flag. A reading function is also included to be able to reload the files back into R. Not so hard to program, but it might be useful to somebody..
write.gslib <- function(dat, file, nodatavalue=-99999)
cat('GSLIB file created in R\n', file=file)
cat(length(names(dat)), file=file, append=TRUE)
cat('\n', file=file, append=TRUE)
write(cbind(names(dat)), file=file, append=TRUE)
for(i in 1:ncol(dat)) dat[is.na(dat[,i]),i] <- nodatavalue
for(i in 1:ncol(dat)) dat[dat[,i]=='NA',i] <- nodatavalue
for(i in 1:ncol(dat)) dat[is.infinite(dat[,i]),i] <- nodatavalue
write.table(dat,file=file, append=TRUE, sep='\t', col.names=FALSE, row.names=FALSE)
read.gslib <- function(filename)
char <- scan(filename, what=character())
nums <- which(as.numeric(char)!='NaN')
nrcol <- as.numeric(char[nums[1]])
begin <- nums[2]
eind <- nums[length(nums)]
nrrows <- (eind-begin+1)/nrcol
indices <- seq(1,nrrows*nrcol-1,nrcol)
mat <- matrix(ncol=nrcol, nrow=nrrows)
i <- 1
while(i <= nrcol)
mat[,i] <- as.numeric(char[(indices+i+begin-2)])
i <- i+1
mat <- as.data.frame(mat)
names(mat) <- c(char[(nums[1]+c(1:nrcol))])

To leave a comment for the author, please follow the link and comment on their blog: Bart Rogiers - Sreigor.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)