Last active
February 8, 2017 09:12
-
-
Save mdsumner/1112c8d89d99d1c13d0989320b612620 to your computer and use it in GitHub Desktop.
Read the data.frame with GDAL. Ignore the geometry, and ignore safety.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Written as a response to http://gis.stackexchange.com/questions/227506/reading-tiger-line-gdb-file-into-r