R select spatial polygon with point inside - r

I have a shapeFile and a spatialPointsDataframe ... I would like to select all polygon where there is point(s) inside, and merge points information in shp#data
word<-readOGR(dsn="data/world/ne_110m_admin_0_countries.shp", layer="ne_110m_admin_0_countries")
xy<-cbind(geoloc$longitude,geoloc$latitude)
spxy<-SpatialPoints(xy)
spdfxy<-SpatialPointsDataFrame(spxy,geoloc)
spdfxy#data<-merge(spdfxy#data,data2000geo)
tps<-!is.na(over(spdfxy,word)) ##retourne the indexe of atribut of y renvois les atribut de word
But after that I don't know how select polygones. i have tried
vitiWord<-word[tps]
but it's doesn't work
for download exemple -> link

I 'have find some thing...
I don't realy know if it work because I would like to use ggplot after and it doesn't work well, but whit
jointure<-over(word,spdfxy) #over from sp library
word#data<-cbind(word#data,jointure)
You have all variable from point in the spatialDataFrame !!

Related

Poly2nb - How to get rid of empty geometries in r

I have r code that I am using to compute Getis-ord Gstatistics. I typically create my shapefile in GIS, then import into r to use with the code. I recently needed to make an edit to my shapefile, which I did in GIS and imported into sas as usual:
tract<-st_read("CBSA2022.shp")
My issue is with the loop portion of my code and the poly2nb feature. Currently it is written as:
for (CBSA in CBSAs) {
temp <- tract[ tract$CBSAFP == CBSA, c("JOIN_ID", variable_of_int)]
names(temp)[2] <- 'black_pop'
#We create the weight matrices within each CBSA now
#We check that there are more than one tract in the CBSA
if ((nrow(temp) > 1)) {
q1<-poly2nb(temp, queen = queen)
if (self_include){ q1 <- include.self(q1) }
Before editing my shapefile in GIS, this worked perfectly with no errors. Now, I receive this error message:
Error in poly2nb(temp, queen = queen) : Empty geometries found
What do you think could be different about my shapefile that I now get this error? And/or how can I fix this? The only difference between this shapefile and the original, is I had to define my spatial join differently when joining my data to spatial polygons in GIS.
I haven't tried anything significant since I am not well versed in r. I did not create this code, but worked with a student (that is no longer available) to create it to be very user friendly for me to use. I've used it numerous times with different shapefiles before my recent edit, and it always worked, just not sure why I now have empty geometries or how to fix it.
Looking on the source code for poly2nb (https://github.com/r-spatial/spdep/blob/main/R/poly2nb.R):
poly2nb <- function(pl, row.names=NULL, snap=sqrt(.Machine$double.eps),
queen=TRUE, useC=TRUE, foundInBox=NULL) {
[...]
if (inherits(pl, "sfc")) {
[...]
if (attr(pl, "n_empty") > 0L)
stop("Empty geometries found")
sf <- TRUE
}
seems, that your temp object is class sfc however, the n_empty attribute isn't updated. Googling around we can find an example: https://github.com/r-spatial/sf/issues/1115. You can check n_empty for your geometries and replace (with 0) those which have value > 0.

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")

how to add my own shape file trajLevel() in openair package R

I am using this following code for plotting the trajectories...........
library(openair)
load("GDASNDL1000m.Rdata")
trajLevel(traj,method="hexbin",col="jet",xbin=40,parameters=NULL,
orientation=c(90,0,0),projection="mercator")
result https://github.com/adeckmyn/maps/files/2667752/GDASNDL1000m.zip
Here, I would like to change the base world map with my own shape file.
my shape file is follows....
z1=maptools::readShapePoly("/home/sateeshm/shapefiles/ncmrwf/india_map")
library(maps)
map(z1)
https://github.com/adeckmyn/maps/files/2667336/World-India.zip
#
Now, the actual question is how to link z1 to trajLevel?
To avoid the hard-coded call to "world" in openair, you wil have to create a new world database in the same file based format as that of the "maps" package.
Probably the simplest way to do this, is to use the mapMaker package. This package is not on CRAN but can be found on github. It is the package I used to create the standard world map. The documentation is minimal, but if you don't care about polygon names etc, you can create a "quick and dirty" world map as follows:
# get your new map as a simple list of polygons (or lines)
z1=maps::map(maptools::readShapePoly("india_map"), plot=FALSE)
# create internal representation
z2=mapMaker::map.make(z1)
# write binary files:
mapMaker::map.export.bin(z2, "/my/path/to/world")
# To make map() call this new database:
library(maps)
worldMapEnv="MYMAP"
Sys.setenv("MYMAP"="/my/path/to/") # don't add the "world" !
now map("world") will draw your version of the world map.

census tract block group shape file

I have a list of lat and long for several thousand members and want to append their census tract block group code(i.e. 36001038141345). My first thought is to plot these members on a map that has a us census block group layer. Then either use an overlay function from one of the mapping packages for example, or instead of using shape files convert file to data frame and use a join function for example from "ggplot" and "ggmap" to match the lat and long to the 14 digit census block group value.
## Example of results: ##
GEOID10 LAT LONG
1. 1005950300123 +31.7908933 -085.5670514
2. 01005950900134 +31.8467221 -085.1462332
3. 01005950800145 +31.9206930 -085.1760317
4. 01005950700156 +31.9440855 -085.2620842
5. 01005950600167 +31.8783526 -085.2729215
6. 01005950100178 +32.0353533 -085.2477678
7. 01005950400189 +31.6794432 -085.5577196
8. 01005950200200 +31.9222753 -085.4498309
9. 01005950500211 +31.7634183 -085.2718649
10. 01027959000222 +33.3093759 -085.8820883
11. 01027959200233 +33.1781831 -086.0215486
12. 01027958900244 +33.3872783 -085.7690615
I am searching for a us census block group shape file to use in R. A shape file that might work is a separate download for all US states using Tiger files at US census site along with the necessary support files (".shp, .dbf, .prj etc.") making using this file problematic because it would result in a couple of hundred needed files.
Also checked the UScensus2010 package but it doesn't yet have the 'install.blkgrp' function set up. I'm reaching out to get some ideas or direction on what is the best way to do this.
Thank you
I found this was the easiest way to download census tract shape files using R:
if (("tigris" %in% rownames(installed.packages()))==FALSE)install.packages("tigris"); library(tigris)
if (("ggplot2" %in% rownames(installed.packages()))==FALSE)install.packages("ggplot2"); library(ggplot2)
census.tracts <- tracts(state="NJ")
plot(census.tracts)
census.tracts.fort <- fortify(census.tracts)
This piece of code will give you a census tract shape file for the state of New Jersey. Late to the party I know, but I hope this process can help others.

Creating Shapefiles in 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!

Resources