I've loaded multiple packages / tried numerous methods to read a .shp. None of the methods work and I'm unable to decipher google related suggestions. Running the code in R, the system freezes and the same code in RStudio.cloud only returns various error messages. A list of the packages and code are below. Ultimately, I'm trying to create maps, join with another file and produce a table of the results. Any suggestions would be appreciated.
library(rgeos)
library(sp)
library(rgdal)
library(maptools)
library(sf)
require(sf)
area <- read_sf(dsn = ".", layer = "2020ATLclip")
require(rgdal)
shape <- readOGR(dsn= ".", layer = "2020ATLclip.shp")
shape <- readOGR(dsn= ".", layer = "tl_2021_13_concity.shp")
library(raster)
l = readShapePoly("2020ATLclip.shp")
l = readShapePoly("tl_2021_13_concity.shp")
atl.poly <- readOGR("./data", layer = "tl_2021-13_concity.shp")
Cannot open layer 2020ATLclip
Error in CPL_read_ogr(dsn, layer, query, as.character(options), quiet, :
Opening layer failed.
In addition: Warning messages:
1: Unable to open /cloud/project/2020ATLclip.shx or /cloud/project/2020ATLclip.SHX. Set SHAPE_RESTORE_SHX config option to YES to restore or create it. (GDAL error 4)
2: Failed to open file /cloud/project/2020ATLclip.shp. It may be corrupt or read-only file accessed in update mode. (GDAL error 4)
>
Error in ogrInfo(dsn = dsn, layer = layer, encoding = encoding, use_iconv = use_iconv, :
Cannot open layer
l = readShapePoly("2020ATLclip.shp")
Error in getinfo.shape(filen) : Error opening SHP file
In addition: Warning message:
readShapePoly is deprecated; use rgdal::readOGR or sf::st_read
> l = readShapePoly("tl_2021_13_concity.shp")
Error in getinfo.shape(filen) : Error opening SHP file
In addition: Warning message:
readShapePoly is deprecated; use rgdal::readOGR or sf::st_read
For both readOGR (from the rgdal package) and st_read (from the newer sf package), when importing a shapefile the dsn= parameter must point to the shp file - with extension *.shp. The layer= parameter is unnecessary with shapefiles. And you must also have the other components of the shapefile format in the same directory: the *.shx, *.dbf, and *.prj. Assuming you have these files in the current working directory, then...
If you insist on using the rgdal library:
library(rgdal)
shape <- readOGR(dsn= "2020ATLclip.shp")
# returns an object of class Spatial*DataFrame from sp
Preferably you should switch to sf, then
library(sf)
shape <- st_read(dsn = "2020ATLclip.shp")
# returns an object of class sf
Related
I've unpacked the following libraries
library(BIOMASS)
library(readr)
library(sp)
library(raster)
library(rgdal)
library(ncdf4)
library(tidyverse)
I've succesfully stacked a tiff file
s1 <- stack('XXX.tif')
I now want to extract this using
s1_e <- extract(s1,pspcoord,method='bilinear')
I get the following warning message when running previous line
In proj4string(x) : CRS object has comment, which is lost in output
NOTE: Earlier in the code i had run the following line concerning proj4string
plotcoord <- SpatialPointsDataFrame(AGCplot[,3:4], AGCplot[,1:2],proj4string=CRS('+proj=longlat'))
pspcoord<-spTransform(plotcoord, CRS('+proj=utm +zone=21'))
Q: What does this warning message mean?
I am a beginner in R and now I am working in the product at NASA: Harmonized Landsat and Sentinel-2. I downloaded the image in .hdf, but when I tried to convert in R to tiff, received an error.
I'm using this code:
library(gdalUtils)
library(rgdal)
library(raster)
gdal_setInstallation(verbose=TRUE)
getOption("gdalUtils_gdalPath")
setwd(dir = "C:/Users/HOME/Documents/TESTE")
getwd()
sds <- get_subdatasets('HLS.L30.T23LLG.2016004.v1.3.hdf')
sds
gdal_translate(sds[1], dst_dataset = "band1.tif", a_nodata = -1000)
This is the error:
Warning message:
running command
'"C:\ProgramData\Anaconda2\Library\bin\gdal_translate.exe" -a_nodata
"-1000" -of "GTiff" "782" "band1.tif"' had status 1
The image can be downloaded here: https://hls.gsfc.nasa.gov/data/v1.3/sites/BAH/L30/2016/23LLG/
I am trying to import an openstreetmaps shape file in R using the rgdal package.
The shape file I downloaded has 5 components in it:
places.cpg
places.dbf
places.prj
places.shp
places.shx
The files can be accessed at the following location:
https://drive.google.com/open?id=0B1ITb_7lHh1EUFVfVWc4ekRfSnc
I have to do the following:
1) Import the shape file
2) Extract lat/long of the point or centroid of shape in case of polygon
3) Attach the lat/long pair to the dbf file to do some analysis
I am stuck in the first stage of import itself, I am running the following code:
shape1 <- readOGR(dsn = "try", layer = "places")
Here 'try' is the folder in my working directory where all the 5 'places' file from openstreetmaps mentioned above are located.
I get the following error when doing this:
Error in readOGR(dsn = "try", layer = "places") : no features found
In addition: Warning message:
In ogrInfo(dsn = dsn, layer = layer, encoding = encoding, use_iconv =
use_iconv, : ogrInfo: all features NULL
I need help with this import. Alternatively if there is a way to directly extract lat/long from one of the places shape file, I can just open the places.dbf file in excel and add the lat/long.
When you are facing troubles with the readOGR() function: Another possibility is to use the maptools package. It creates SpatialXXXDataFrames so you can use all the functions from rgeosetc.
library(maptools)
setwd("/your/data/path/")
places <- readShapeSpatial("places")
# ... your geospatial functions, like
plot(places)
probably you will have to adjust the projection of the spatial data. For OSM-Data you will need to find the proj4string for WGS84 (or EPSG:4326) at spatialreference.org.
Thus you can adjust your projection in R:
proj4string(places) <- CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")
For the calculation/"extraction" of polygon centroids see this post.
You need to use the shapefile (.shp) as the DSN. Turning the SpatialPointsDataFrame into a "normal" data.frame will give "ugh" column names
for lang & lat, so you can rename them to make them more usable:
library(sp)
library(rgdal)
places <- readOGR("places/places.shp", "places", verbose=FALSE, stringsAsFactors=FALSE)
places_df <- setNames(as.data.frame(places),
c("osm_id", "name", "type", "population", "longitude", "latitude"))
head(places_df)
## osm_id name type population longitude latitude
## 1 25431184 Stockertown village NA -75.26156 40.75446
## 2 25716549 Mechanicsburg village NA -77.00473 40.21020
## 3 25762119 Mansfield hamlet NA -77.07929 41.80569
## 4 25840249 New Columbia hamlet NA -76.87368 41.03368
## 5 25840585 Williamsport town 29381 -77.00277 41.24933
## 6 25930002 Hershey town 14257 -76.65060 40.28549
I couldn't get this package to work but the package "shapefiles" did the work for me. It has a read.shapefile function that imports shapefiles.
I have a shape file, uploaded at the following path:
https://drive.google.com/open?id=0B1ITb_7lHh1EUFVfVWc4ekRfSnc
I imported the data using the "read.shapefiles" function in "shapefiles" package:
landuse<- read.shapefile("landuse")
I now need to extract the lat/long centroids of all the shapes within the landuse object and add it to the landuse$dbf dataframe
I tried two things:
lu_df<-coordinates(landuse)
lu_df<-SpatialPoints(landuse)
Both gave me the following error:
Error in coordinates(as.data.frame(obj)) :
error in evaluating the argument 'obj' in selecting a method for function 'coordinates': Error in data.frame(record = 1L, content.length = 80L, shape.type = 5L, :
arguments imply differing number of rows: 1, 4, 7
I am not sure on how to proceed.
First, I recommend using the rgdal package for spatial data. The readOGR and writeOGR functions provide nice Shapefile handling (like input and output of projections etc.).
UPDATE:
Since this is not working for #Shaz (see error in comments), the maptoolsfunction readShapePoly()was utilized. Also see this post.
To your problem: The rgeos package provides a function gCentroid() which calculates the centroid of your polygons. The solution looks something like this:
setwd("/path/to/your/shapefile/")
library(maptools)
library(rgeos)
landuse <- readShapePoly("landuse")
centr <- gCentroid(landuse, byid = TRUE)
# create SpatialPointsDataFrame to export via writeOGR
# positive side effect: All data from landuse#data joined to centr#data
centr <- SpatialPointsDataFrame(centr, data= landuse#data)
writeOGR(centr, ".", "landuse_centroids", driver = "ESRI Shapefile")
I've created the following script to get the coastline of Denmark
# Get Shapefiles for Coastline
shpurl <- "http://download.geofabrik.de/europe/denmark-latest.shp.zip"
tmp <- tempfile(fileext=".zip")
download.file(shpurl, destfile = tmp)
files <- unzip(tmp, exdir=getwd())
# Load & plot shapefile
library(maptools)
shp <- readShapePoly(files[grep(".shp$", shpurl)])
plot(shp)
This should give me the outline of Denmark, however, I keep getting the following error:
Error in plot.window(...) : need finite 'ylim' values
In addition: Warning messages:
1: In xy.coords(x, y, xlabel, ylabel, log) : NAs introduced by coercion
2: In min(x) : no non-missing arguments to min; returning Inf
3: In max(x) : no non-missing arguments to max; returning -Inf
Any help or directions is appreciated.
Have a look at your files value:
> length(files)
[1] 41
The files you are downloading have number of shape files for various geographies. For instance the code:
require(rgdal)
shp <- readOGR(dsn = "whereIsavedyourStuff/Stacks", layer = "roads")
will execute properly. But you will need to specify, which of the sourced shape files you want to read.
As a side point, with respect to reading files from the net, I would suggest that you have a look at this code:
# Download an read US state shapefiles
tmp_shps <- tempfile(); tmp_dir <- tempdir()
download.file("http://www2.census.gov/geo/tiger/GENZ2014/shp/cb_2014_us_state_20m.zip",
tmp_shps)
unzip(tmp_shps, exdir = tmp_dir)
# Libs
require(rgdal)
# Read
us_shps <- readOGR(dsn = tmp_dir, layer = "cb_2014_us_state_20m")
Irrespectively, of what method to read shape files you decide to use you have to specify path and file name. In terms of the provided code in readOGR this is fulfilled by dns and layer options. In your code you used files[grep(".shp$", shpurl)], file names within your 195MB archive, do not corresponds to the URL. You have a few options here:
You can download this files and unpack as you did, list names of all the files that are *.shp, take the file names and pass them in the loop to a list where you would read all combinations (in effect you need a number of files to read each layer)
Better, specify the layer you want to read similarly to the code provided above.