Skip to content

Instantly share code, notes, and snippets.

@mdsumner
Last active February 8, 2017 09:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdsumner/1112c8d89d99d1c13d0989320b612620 to your computer and use it in GitHub Desktop.
Save mdsumner/1112c8d89d99d1c13d0989320b612620 to your computer and use it in GitHub Desktop.
Read the data.frame with GDAL. Ignore the geometry, and ignore safety.
# WARNING: do not use this
# it's torn rudely from rgdal::readOGR and does virtually none of the careful
# checks and options provided by that function, amongst the things we ignore are
# conversion of implied 64 bit integers, dropping unsupported fields, and returning nothing
# but an error if there's no non-NULL geometries
#
# If you want some more of the options you can investigate what readOGR has to go through and do that as well
# (much of which is in R, not C).
# This is unsupported, it may turn up in some form in a package, but don't use it then either.
library(rgdal)
dont_use_this_egregious_hack_to_read_a_dataframe_with_GDAL <- function(dsn, layer, stringsAsFactors = FALSE) {
fids <- ogrFIDs(dsn = dsn, layer = layer)
if (attr(fids, "i") != attr(fids, "nf")) {
retain <- 1:attr(fids, "i")
afids <- 0:(attr(fids, "nf") - 1)
deleted <- afids[!(afids %in% fids[retain])]
warning(paste("Deleted feature IDs: ", paste(deleted,
collapse = ", ")))
fids <- fids[retain]
}
ogr_info <- ogrInfo(dsn = dsn, layer = layer,
encoding = NULL, use_iconv = FALSE, swapAxisOrder = FALSE,
require_geomType = NULL)
if (is.null(ogr_info$nListFields)) {
nListFields <- 0
} else {
nListFields <- ogr_info$nListFields
}
integer64 <- "no.loss"
int64 <- switch(integer64, allow.loss = 1L, warn.loss = 2L,
no.loss = 3L)
iflds <- as.integer((1:ogr_info$nitems) - 1)
attr(iflds, "nListFields") <- as.integer(nListFields)
nflds <- length(iflds)
attr(iflds, "nflds") <- as.integer(nflds)
attr(iflds, "int64") <- as.integer(int64)
dlist <- .Call("ogrDataFrame", as.character(dsn), as.character(layer),
as.integer(fids), iflds, PACKAGE = "rgdal")
as.data.frame(dlist, stringsAsFactors = stringsAsFactors)
}
## TESTS, write to CSV and read with GDAL
write.csv(iris, "iris.csv", row.names = FALSE)
dont_use_this_egregious_hack_to_read_a_dataframe_with_GDAL("iris.csv", "iris")
## read from GML (may not be available on your system, true of most drivers/formats)
dsn <- system.file("vectors/airports.gml", package = "rgdal")[1]
dont_use_this_egregious_hack_to_read_a_dataframe_with_GDAL(dsn=dsn, layer="airports")
@mdsumner
Copy link
Author

mdsumner commented Feb 8, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment