R and the Geostatistical Software Library data format
[This article was first published on Bart Rogiers - Sreigor, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
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))]) return(mat) }
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 about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.