Creating Shapefiles in R - r

I'm trying to create a shapefile in R that I will later import to either Fusion Table or some other GIS application.
To start,I imported a blank shapefile containing all the census tracts in Canada. I have attached other data (in tabular format) to the shapefile based on the unique ID of the CTs, and I have mapped my results. At the moment, I only need the ones in Vancouver and I would like to export a shapefile that contains only the Vancouver CTs as well as my newly attached attribute data.
Here is my code (some parts omitted due to privacy reasons):
shape <- readShapePoly('C:/TEST/blank_ct.shp') #Load blank shapefile
shape#data = data.frame(shape#data, data2[match(shape#data$CTUID, data2$CTUID),]) #data2 is my created attributes that I'm attaching to blank file
shape1 <-shape[shape$CMAUID == 933,] #selecting the Vancouver CTs
I've seen other examples using this: writePolyShape to create the shapefile. I tried it, and it worked to an extent. It created the .shp, .dbf, and .shx files. I'm missing the .prj file and I'm not sure how to go about creating it. Are there better methods out there for creating shapefiles?
Any help on this matter would be greatly appreciated.

Use rgdal and writeOGR. rgdal will preserve the projection information
something like
library(rdgal)
shape <- readOGR(dsn = 'C:/TEST', layer = 'blank_ct')
# do your processing
shape#data = data.frame(shape#data, data2[match(shape#data$CTUID, data2$CTUID),]) #data2 is my created attributes that I'm attaching to blank file
shape1 <-shape[shape$CMAUID == 933,]
writeOGR(shape1, dsn = 'C:/TEST', layer ='newstuff', driver = 'ESRI Shapefile')
Note that the dsn is the folder containing the .shp file, and the layer is the name of the shapefile without the .shp extension. It will read (readOGR) and write (writeOGR) all the component files (.dbf, .shp, .prj etc)

Problem solved! Thank you again for those who help!
Here is what I ended up doing:
As Mnel wrote, this line will create the shapefile.
writeOGR(shape1, dsn = 'C:/TEST', layer ='newstuff', driver = 'ESRI Shapefile')
However, when I ran this line, it came back with this error:
Can't convert columns of class: AsIs; column names: ct2,mprop,mlot,mliv
This is because my attribute data was not numeric, but were characters. Luckily, my attribute data is all numbers so I ran transform() to fix this problem.
shape2 <-shape1
shape2#data <- transform(shape1#data, ct2 = as.numeric(ct2),
mprop = as.numeric(mprop),
mlot = as.numeric(mlot),
mliv = as.numeric(mliv))
I tried the writeOGR() command again, but I still didn't get the .prj file that I was looking for. The problem was I didn't specified the coordinate systems for the shapefile when I was importing the file. Since I already know what the coordinate system is, all I had to do was define it when importing.
readShapePoly('C:/TEST/blank_ct.shp',proj4string=CRS("+proj=longlat +datum=WGS84")
After that, I re-ran all the things I wanted to do with the shapefile, and the writeOGR line for exporting. And that's it!

Related

How to edit cells Shapefile in R?

I downloaded a shapefile of the world map from gadm, however, there are typos that happen with importing the shape file. For example "Aland" shows up as "Ã…land" in the shapefile. There are handful of countries I want to make changes to.
world map shapefile, the one that says "You can also download this version as six separate layers (one for each level of subdivision/aggregation), as a geopackage database or as shapefiles" :https://gadm.org/download_world.html
I imported the shapefile using:
worldmap <- readOGR("file/gadm36_0.shp")
I tried using the following code:
levels(wordlmap$NAME_0)[5] <- "Aland"
However I got this message:
Error in `levels<-`(`*tmp*`, value = c(NA, NA, NA, NA, "Aland")) :
factor level [2] is duplicated
Could you suggest how this code can be made better or an alternative.Thanks in advance
Since you did not provide a shapefile, I just worked with a publicly-available shapefile of Indian states. The long and short of it is to use the sf package. It loads shapefiles as (quasi) dataframes--with the longitudes and latitudes stored in the geometry variable. Then, you should be in familiar territory. Here is some code to change a state name variable:
# clear environment
rm(list=ls(all=TRUE))
# let's take admin 1 (states)
# note: already in WGS84 format
library(sf)
india_shape <- st_read("india_shape/gadm36_IND_1.shp", stringsAsFactors=FALSE)
# Let's pick something to change (state name)
> india_shape$NAME_1[1]
[1] "Andaman and Nicobar"
# Now change it
> india_shape$NAME_1[1] <- "New State Name"
> india_shape$NAME_1[1]
[1] "New State Name"
I can tell you a few things about how I manage those shape files downloaded from, www.gadm.org site.
First, a shape file has several other related files that do not have the .shp extension. These files must remain together in the same folder. All these files are included in the shape zip file from the gadm website.
The rgdal package provides the, readOGR() function. This function is normally in the form: readOGR(dsn = " ", layer = " " )
The, dsn is "data source name". Use quotes.
The, layer is the name of shape file without the .shp extension. Use quotes.
Proper file management is required to make things work and to maintain good file management. I already have a USA folder within my dataset folder.
I just downloaded the gadm USA shape file. So first, I will add a new folder, named USA_map, in the USA folder. And also create a new folder named, data in this new USA_map folder.
C:/python/datasets/usa/usa_map/data # usa_map/data are new
Copy the downloaded gadm36_USA_shp.zip from the "download" folder and paste into the new "USA_map" folder. Then, open the GADM zip folder and extract the entire contents of the zip folder into the new "data" folder. Then the zip file can new be deleted because all the files have been copied into the "data" folder. All's done and ready.
Now use the readOGR() function to read the shape file and assign to new variable, called usmap
usmap <- readOGR(dsn = "c:/python/datasets/USA/USA_map/data", layer = "gadm36_USA_1")
The trick is to follow the correct file management so the readOGR() function works as designed.
Next, you need to learn how to navigate through this type of data.
If there is more than one polygon with the same wrong name, you can make like that :
w <- length(wordlmap)
for (i in 1:w){
if (wordlmap$NAME_0[i] == "Ã…land") {
wordlmap$NAME_0[i] <- "Aland"
}}

How to save a shapefile after transform the crs from the existing shapefile in R?

I am trying with this code but it is not working. Please help me with this issue. Thank you.
readshp <- readOGR(file.path(nhgisdir, “file1.shp”))`enter code here`
trshape <- spTransform(readshp, "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0”)
writeOGR(trshape, file.path(workdir,”file1_tr.shp"), driver="ESRI Shapefile”) # This one goes wrong!!
Make sure you specify all required arguments of the functions you are using to make them work. Also make sure you use only one type of quotation marks to open and close your strings. Your question uses two different types ” and ", which probably causes errors since r does not know where your commands start and end.
Now the functions to read shapefiles readOGR needs some arguments specified: That is dsn, the directory of your shapefiles and layer, the actual shapefile but without a file extension. The function writeOGR works similarly, but has different behaviour depending on the driver you use. For ESRI Shapefile, the argument dsn needs to be the filename you want to save your shapefile as including an extension. And layer will be the filename without an extension.
All of this info, and which type of arguments need to be specified for which driver, is in the documentation of rgdal. And there are numerous tutorials out there, e.g. this one by Dr. Emily Burchfield
Finally, here is some example code:
library(rgdal)
in_shape <- readOGR(dsn="/path/to/shape/", layer="shapefile")
transformed_shape <- spTransform(in_shape, CRS("+proj=longlat +ellps=GRS80"))
writeOGR(transformed_shape, dsn="/path/to/shape/exported_shapefile.shp", layer="exported_shapefile", driver="ESRI Shapefile")

Create a Map in Plotly Using Two Files With plot_mapbox

Thanks for reading my post. I am trying to create one map in Plotly using R by layering data from 2 data sources and the function plot_mapbox. The map will show locations of stores in zoned business districts.
test is a geoJSON file of zoning districts
test2 is a csv file of business locations using longitude and latitude coordinates
I've tried layering the data and combining two geoJSON files. The first file is a geoJSON file (business zones)and the second file is a .csv (store locations) with longitude and latitude. I converted the csv file to a geoJSON file and then tried to merge them. I would really need to append them since they don't have a common key.
library(plotly)
library(geojsonR)
library(sf)
test<-st_read("D:/SPB/Zoning_Detailed.geojson", quiet=FALSE, , geometry_column="SHAPE_Area")
test2<-read.csv("D:/SPB/Pet_Bus.csv")
One layering exampe
plot_mapbox(data=test, color=~ZONING) %>%
add_markers(data=test2, x=~Longitude, y=~Latitude)
layout(mapbox=list(style = "streets"))
One merge example (only the first file is added in merge)
files Zoning_Detailed.geojson and Pet_Bus.geojson are in the Merge folder. I
converted Pet_Bus.csv to a geojson file.
This should really be append since test and test2 are independent of each other, but in same city.
merge_files("D:/SPB/Merge/", "D:/SPB/Merge/test7.geojson")

Error using fortify() in ggplot2

I am creating a map using the zip code information from the census data together with data that I have for each zip code.
I obtained the shapefiles for the zip codes from https://www.census.gov/geo/maps-data/data/tiger-cart-boundary.html.
I successfully read in the shapefiles using readOGR with the following code:
Zip = readOGR("C:\\...pathname....\\cb_2013_us_zcta510_500k.shp")
I am running into a problem when I try to use fortify so that I can combine the information from the shapefile with my data.
names(Zip)
[1] "ZCTA5CE10" "AFFGEOID10" "GEOID10" "ALAND10" "AWATER10"
test = ggplot2::fortify(Zip, region="AWATER10")
Error in fortify.SpatialPolygonsDataFrame(Zip, region = "AWATER10") :
`region' not supported
The error is replicated when I try all of the results from names(Zip). I am not sure which column contains the zip code information that I am interested in, so I just tried all of them.
My ultimate goal is to use the zip code information with ggmap to fill in the zip codes with different colors based on information in my data.

readOGR() cannot open file

wmap <- readOGR(dsn="~/R/funwithR/data/ne_110m_land", layer="ne_110m_land")
This code is not loading the shape file and error is generated as
Error in ogrInfo(dsn = dsn, layer = layer, encoding = encoding, use_iconv = use_iconv, :
Cannot open file
I am sure that the directory is correct one. At the end / is also not there and layer name is also correct.
Inside the ne_110m_land directory files I have are:
ne_110m_land.dbf
ne_110m_land.prj
ne_110m_land.shp
ne_110m_land.shx
ne_110m_land.VERSION.txt
ne_110m_land.README.html
You could have shown that you have the right path with:
list.files('~/R/funwithR/data/ne_110m_land', pattern='\\.shp$')
file.exists('~/R/funwithR/data/ne_110m_land/ne_110m_land.shp')
perhaps try:
readOGR(dsn=path.expand("~/R/funwithR/data/ne_110m_land"), layer="ne_110m_land")
or a simpler alternative that is wrapped around that:
library(raster)
s <- shapefile("~/R/funwithR/data/ne_110m_land/ne_110m_land.shp")
Update:
rgdal has changed a bit and you do not need to separate the path and layer anymore (at least for some formats). So you can do
x <- readOGR("~/R/funwithR/data/ne_110m_land/ne_110m_land.shp")
(perhaps still using path.expand)
Also, if you are still using readOGR you are a bit behind the times. It is better to use terra::vect or sf::st_read.
I had the same error. To read in a shapefile, you need to have three files in your folder: the .shp, .dbf and .shx files.
For me, the command returned the Cannot open layer error when I included the dsn and layer tags.
So when I included it all just as
readOGR('~/R/funwithR/data/ne_110m_land/ne_110m_land.shp')
it worked.
Note that my file was a gjson, so I've only seen this with
readOGR('~/R/funwithR/data/ne_110m_land/ne_110m_land.gjson')
the Mandatory files should be all in the same directory
.shp — shape format
.shx — shape index format;
.dbf — attribute format;
then we can just give the path as a parameter to the function it will work.
global_24h =readOGR( '/Users/m-store/Desktop/R_Programing/global_24h.shp')
Here's what worked for me (with a real example)
require(rgdal)
shape <- readOGR(dsn = "1259030001_ste11aaust_shape/STE11aAust.shp", layer = "STE11aAust")
The exact data is available here (download the .zip file called 'State and Territory ASGC Ed 2011 Digital Boundaries in MapInfo Interchange Format')
the syntax: library(raster)
s <- shapefile("~/R/funwithR/data/ne_110m_land/ne_110m_land.shp") worked perfectly! todah rabah!
As I commented in other post (Error when opening shapefile), using file.choose() and selecting manually will help in the case one file selection is needed. Apparently is related with NaturalEarth shapefiles
it seems to me that this is the solution, at least before uploading it to the cloud
######################################
# Server
######################################
#I tell R where to extract the data from
#Le digo al R donde debe jalar la data
dirmapas <- "E:/Tu-carpeta/Tu-sub-carpeta/ESRI" #Depende donde tengas tú tus
#archivos de cartografía
setwd(dirmapas)
#The raw map
# El mapa de polígonos en blanco y negro
departamentos<-readOGR(dsn="BAS_LIM_DEPARTAMENTO.shp", layer="BAS_LIM_DEPARTAMENTO")

Resources