When I try to read shapefiles in a loop in R, it always reports
"Error in .local(x, ...) : file.exists(extension(x, ".shp")) is not
TRUE " .
The code that I use to read the shapefile is
"city.i=shapefile(citynames1[i]) "
where citynames1 is a vector of shapefile names with the extension of .shp.
Thanks very much for your help.
The problem is connected with locale setting on your PC. In my case sf package were able to write files with Chinese characters, please see the code below:
# simulation
library(sf)
file_name <- system.file("shape/nc.shp", package="sf")
nc <- st_read(file_name)
# write shape
st_write(nc, "你好.shp")
# clear & read
rm(list = ls())
nc <- st_read("你好.shp")
plot(nc)
Output:
Related
I'm trying to select & plot just one of these 9 attributes from my shape file, but nothing seems to work.
Could you help?
enter image description here
It helps if you make a fully reproducible example so that fixers can run the code and be certain that they have resolved the issue.
Here is an example that you will have to modify for your own needs.
library(sf)
fname <- system.file("shape/nc.shp", package="sf") # read a shape file that comes with the sf package
nc <- st_read(fname)
plot(nc) # plot all the data
plot(nc['AREA']) # plot one of the attributes
I was trying to convert a dataset from netcdf to csv format using R.
although I have installed 'raster and 'netcdf4' in R.
but still it doesn't find nc.brick.
rm(list=ls())
library(raster)
library(ncdf4)
nc.brick <- brick(file.choose)
dim(nc.brick)
nc.df <- as.data.frame(nc.brick[[1]],xy=T)
head(nc.df)
write.csv(nc.df,file.choose())
test <- read.csv(file.choose())
Can you see the difference between your usage of file.choose in these two lines:
nc.brick <- brick(file.choose)
write.csv(nc.df,file.choose())
there's your problem.
I am using John Baumgrtner's gdal_polygonizeR (https://johnbaumgartner.wordpress.com/2012/07/26/getting-rasters-into-shape-from-r/) to covert rasters to polygons in R. Aside - I tried raster pkg rasterToPolygons function and it took forever; gdal_polygonizeR is way faster. Anyways, I have a list of 533 raster files (different extents) that I want to convert to polygons. The gdal_polygonizeR function works when a single list element is called, but I have tried to use it on all list elements using lapply and get an error message. See code below:
#path to folder containing all .tif raster files
dir <- "/path/to/raster/files"
#create a list of the files in the folder
files <- list.files(path = dir, pattern = ".tif$")
#use lapply to import/create list of all files in folder
rasterl_50 <- lapply(paste0(dir, files), raster)
#test gdal_polygonizeR function on single list element
gdal_polygonizeR(rasterl_50[[1]]) #works properly
#loop thru all elements in list
lapply(rasterl_50, gdal_polygonizeR)
Output = the first six (6) elements seem to run OK, but I get the following error msg at [[7]]:
wfp1 <- gdal_polygonizeR(rasterl_50[[1]])
Creating output /var/folders/s9/pm92gdl94h18k4n6026cb8x00000gn/T//RtmpvRRvA4/file23d4dc99d8d.shp of format ESRI Shapefile.
0...10...20...30...40...50...60...70...80...90...100 - done.
wfp2 <- gdal_polygonizeR(rasterl_50[[2]])
Creating output /var/folders/s9/pm92gdl94h18k4n6026cb8x00000gn/T//RtmpvRRvA4/file23d7698a853.shp of format ESRI Shapefile.
0...10...20...30...40...50...60...70...80...90...100 - done.
wfp3 <- gdal_polygonizeR(rasterl_50[[3]])
Creating output /var/folders/s9/pm92gdl94h18k4n6026cb8x00000gn/T//RtmpvRRvA4/file23d30d4d703.shp of format ESRI Shapefile.
0...10...20...30...40...50...60...70...80...90...100 - done.
wfp4 <- gdal_polygonizeR(rasterl_50[[4]])
Creating output /var/folders/s9/pm92gdl94h18k4n6026cb8x00000gn/T//RtmpvRRvA4/file23d24036d07.shp of format ESRI Shapefile.
0...10...20...30...40...50...60...70...80...90...100 - done.
wfp5 <- gdal_polygonizeR(rasterl_50[[5]])
Creating output /var/folders/s9/pm92gdl94h18k4n6026cb8x00000gn/T//RtmpvRRvA4/file23d4683ed87.shp of format ESRI Shapefile.
0...10...20...30...40...50...60...70...80...90...100 - done.
wfp6 <- gdal_polygonizeR(rasterl_50[[6]])
Creating output /var/folders/s9/pm92gdl94h18k4n6026cb8x00000gn/T//RtmpvRRvA4/file23d4e23b4d1.shp of format ESRI Shapefile.
0...10...20...30...40...50...60...70...80...90...100 - done.
wfp7 <- gdal_polygonizeR(rasterl_50[[7]])
Creating output /var/folders/s9/pm92gdl94h18k4n6026cb8x00000gn/T//RtmpvRRvA4/file23d6791d108.shp of format ESRI Shapefile.
0...10...20...30...40...50...60...70...80...90...100 - done.
Error in readOGR(dirname(outshape), layer = basename(outshape), verbose = !quiet) :
no features found
In addition: Warning message:
In ogrFIDs(dsn = dsn, layer = layer) :
Show Traceback
Rerun with Debug
Error in readOGR(dirname(outshape), layer = basename(outshape), verbose = !quiet) :
no features found
#
If anyone has ideas for a solution using lapply or a for loop etc., please reply. Thanks
Solution: I had to run gdal_polygonizeR on each individual list element, and found that several raster files in the list contained no values (this resulted from reclassify function applied to rasters prior). I removed these files from the list, and lapply worked. Here is the code:
#remove 'no value' elements from the list
new_rastlist <-
rasterlist[c(-7,-14,-36,-89,-191,-310,-432,-436,-476,-493,-494,-501)]
#then try again to use lapply
polyl <- lapply(rastlist, gdal_polygonizeR)
UPDATE:
Even better, remove rasters with all NAs first with this:
batch_reclass <- function(rastlist){
for (i in 1:length(wfrastlist)) {
#read in raster
r <-raster(paste0("/path/to/rasterfiles/", rastlist[i]))
#perform the reclassifcation
rc <- reclassify(r, rclmat)
#write each reclass to a new file
if (!is.na(minValue(rc))) {
writeRaster(rc, filename = paste0("/path/to/new/rasterfiles/", "rc_",
rastlist[i]), format="GTiff", overwrite=TRUE)
}}
}
#run the function
batch_reclass(rastlist)
I am new to R and NetCDF files. I am trying to open data on surface sea temperatures that are in a .nc file from here. My code is as follows:
rm(list=ls())
#install.packages(c("netcdf", "chron", "RColorBrewer", "lattice"))
library(chron)
library(RColorBrewer)
library(lattice)
library(ncdf4)
# set path and filename
ncpath <- "C:/Users/Mihir Sharma/Dropbox/data/"
ncname <- "20140101023458-NCEI-L3C_GHRSST-SSTskin-AVHRR_Pathfinder-PFV5.3_NOAA19_G_2014001_night-v02.0-fv01.0"
ncfname <- paste(ncpath, ncname, ".nc", sep="")
dname <- "tmp" # note: tmp means temperature (not temporary)
# open a NetCDF file
ncin <- nc_open(ncfname)
But I am getting the following error:
Error in nc_open(ncfname) :
Error in nc_open trying to open file C:/Users/Mihir Sharma/Dropbox/1 EPIC/MPA/data/20140101023458-NCEI-L3C_GHRSST-SSTskin-AVHRR_Pathfinder-PFV5.3_NOAA19_G_2014001_night-v02.0-fv01.0.nc
I have followed the code from here and here. what am I doing wrong?
Many thanks,
Mihir
Path problems when using someone else's code:
# set path and filename
ncpath <- "C:/Users/Mihir Sharma/Dropbox/data/"
When you're following code on a blog or tutorial, if it's written well, they'll use a platform independent way to describe, but often they won't.
The platform independent way to write a path is:
file.path("Users", "Mihir Sharma", "Dropbox", "data"). This will always use the correct file separator for your Platform, a value stored in .Platform$file.sep
I have read a shapefile using readShapePoly in the maptools package, but cannot read that same file with readOGR. I am hoping someone may be able to help me read the shapefile with readOGR.
I downloaded the file orcounty.shp from here: http://geography.uoregon.edu/geogr/topics/maps.htm
I also downloaded the associated files: orcounty.shx, orcounty.sbx, orcounty.sbn, and orcounty.dbf and put all five files in the folder: c:/users/mark w miller/gis_in_R/shapefile_example/
The following code reads the shapefile and displays some attributes:
library(maptools)
setwd('c:/users/mark w miller/gis_in_R/shapefile_example/')
# Oregon county census data (polygons)
orcounty.poly <- readShapePoly('orcounty.shp', proj4string=CRS("+proj=longlat"))
orcounty.line <- readShapeLines('orcounty.shp', proj4string=CRS("+proj=longlat"))
# see projection
summary(orcounty.poly)
Object of class SpatialPolygonsDataFrame
Coordinates:
min max
x -124.55840 -116.46944
y 41.98779 46.23626
Is projected: FALSE
proj4string : [+proj=longlat]
Data attributes:
However, when I try to read that same shapefile using the following code I receive an error:
library(rgdal)
# read shapefile
oregon.map <- readOGR(dsn="c:/users/mark w miller/gis_in_R/shapefile_example/", layer="orcounty")
# convert to dataframe
oregon.map_df <- fortify(oregon.map)
The error message says:
Error in ogrInfo(dsn = dsn, layer = layer, encoding = encoding, use_iconv = use_iconv) :
Cannot open file
I can read Natural Earth http://www.naturalearthdata.com/ shapefiles using:
library(rgdal)
setwd("c:/users/mark w miller/gis_in_R/")
# read shapefile
wmap <- readOGR(dsn="ne_110m_physical", layer="ne_110m_land")
So, apparently there is a difference between the Natural Earth shapefiles and the Oregon shapefile orcounty.shp.
Thank you for any advice on how to read orcounty.shp with readOGR. My question is similar to the question here: rgdal / readOGR - unable to read shapefile from .zip
Try to remove your last '/' from file path.
readOGR(dsn = 'c:/users/mark w miller/gis_in_R/shapefile_example',
layer = 'orcounty')
For anyone ending up here with this error on a Linux box, I found the problem was using a home path shortcut. i.e.
# Works
readOGR(dsn="/home/user/dir", layer="file")
# Doesn't work
readOGR(dsn="~/dir", layer="file")
I have no idea why.
I used the file ne_110m_land
Try with this:
setwd('D:/JMSR/codes.R/mapas')
unzip("ne_110m_land.zip")
ogrInfo(".", "ne_110m_land")
wmap <- readOGR(".", "ne_110m_land")
raster::shapefile wraps around readOGR to take care of paths and tildes; just pass the full file name.
library(raster)
x <- shapefile("c:/users/orcounty.shp')
or
y <- shapefile("~/users/orcounty.shp")