How to Reorder Formal Class Spatial Polygons - r

I'm looking for a way to re-order a set of Formal Class Spatial Polygons using
I'm using US Census data (Limited to Texas) and want to create 33 polygons out of different county combinations.
library(tmap)
library(maptools)
library(ggplot2)
library(rgeos)
library(sp)
library(mapdata)
library(rgdal)
library(raster)
# Download the map of texas and get the LMAs boundaries
# Download shape
f <- tempfile()
download.file("http://www2.census.gov/geo/tiger/GENZ2010/gz_2010_us_050_00_20m.zip", destfile = f)
unzip(f, exdir = ".")
US <- read_shape("gz_2010_us_050_00_20m.shp")
# Select only Texas
Texas <- US[(US$STATE %in% c("48")),]
# Load the LMA append data
LMAs = read.table('LMA append data.csv',header=T, sep=',')
# Append LMA data to Texas shape
Texas$FIPS <- paste0(Texas$STATE, Texas$COUNTY)
Texas <- append_data(Texas, LMAs, key.shp = "FIPS", key.data = "FIPS")
Texas <- Texas[order(Texas$LMA),]
# Create shape object with LMAs polygons
Texas_LMA <- unionSpatialPolygons(Texas, IDs=Texas$LMA)
I've tried converting Texas_LMA into a SpatialPolygonsDataFrame with
# Create shape object with LMAs polygons
Texas_LMA <- unionSpatialPolygons(Texas, IDs=Texas$LMA)
spp <- SpatialPolygonsDataFrame(Texas_LMA,data=matrix(1:33,nrow=33,ncol=1))
But that hasn't worked for me.

Your question is not very clear. But I think this is what you are after:
library(raster)
f <- tempfile() download.file("http://www2.census.gov/geo/tiger/GENZ2010/gz_2010_us_050_00_20m.zip", destfile = f)
unzip(f, exdir = ".")
US <- shapefile("gz_2010_us_050_00_20m.shp")
Texas <- US[(US$STATE %in% c("48")),]
LMAs = read.csv('LMA append data.csv')
Texas$FIPS <- paste0(Texas$STATE, Texas$COUNTY)
You did not provide the LMA data, so guessing a bit from here:
Texas <- merge(Texas, LMAs, by="FIPS")
Texas_LMA <- aggregate(Texas, by='LMA')

shapefilename[order(shapefilename$column_name),]

Related

How to filter only one polygon in a map in R

I am generating a map below using a shapefile file. The map refers to a state of a specific country. Now I would like to show the map only one municipality. In this case, I would like the municipality called Ponta Grossa. I believe you have to do something like: NM_MUNICIP == PONTA GROSSA. NM_MUNICIP is an attribute of the shapefile.
> names(shp)
[1] "NM_MUNICIP" "CD_GEOCMU"
Executable code below:
library(rgdal)
temp <- tempfile()
temp2 <- tempfile()
download.file("https://geoftp.ibge.gov.br/organizacao_do_territorio/malhas_territoriais/malhas_municipais/municipio_2015/UFs/PR/pr_municipios.zip",temp)
unzip(zipfile = temp, exdir = temp2)
shp <- readOGR(temp2)
plot(shp)
You can subset by the attribute to return only PONTA GROSSA:
shp_subset <- shp[shp$NM_MUNICIP == "PONTA GROSSA",]
plot(shp_subset)
Or you can also use subset:
subset(shp, NM_MUNICIP == "PONTA GROSSA") |>
plot()

How to save dataframe geometry to a shapefile in R

I want to save route_dhdb_sf in SHP file, it looks like this :
My problem is the geometry column.
The R code :
library(sf)
library(ggplot2)
library(stplanr)
# Read shapefile
nl_rails_sf <- sf::st_read("~/netherlands-railways-shape/railways.shp")
# Data frame with station locations
stations_df <- data.frame(station = c("Den Haag", "Den Bosch"),
lat = c(52.080276, 51.690556),
lon = c(4.325, 5.293611))
# Create sf object
stations_sf <- sf::st_as_sf(stations_df, coords = c("lon", "lat"), crs = 4326)
# Find shortest route
slnetwork <- SpatialLinesNetwork(nl_rails_sf)
find_nodes <- find_network_nodes(sln = slnetwork,
x = stations_df$lon,
y = stations_df$lat,
maxdist = 2e5)
route_dhdb_df <- data.frame(start = find_nodes[1], end = find_nodes[2])
route_dhdb_sf <- sum_network_links(sln = slnetwork, routedata = route_dhdb_df)
How do I save this route_dhdb_sf to a shape file?
#Code of mharinga
Normally you can use:
sf::st_write(route_dhdb_sf,"~/netherlands-railways-shape/route_dhdb_sf.shp")
If you tried it, and if it did not work (you got an error message), you can try to save to other formats e.g. geosjon by editing the suffix like this:
sf::st_write(route_dhdb_sf,"~/netherlands-railways-shape/route_dhdb_sf.geojson")

Display wind direction over wind magnitude in R using Levelplot

I have converted U and V component of wind to wind direction and magnitude. But didn't able to map this data using levelplot.
library(raster)
library(rgdal)
library(rasterVis)
library(lattice)
library(grid)
Ucomplist <- list.files(path = "F:/ShareBoth/yearly_variable_data/rasters/Ucomp_annual/Ucomp_annual/", full.names = TRUE)
length(Ucomplist)
U <- brick(Ucomplist)
Vcomplist <- list.files(path = "F:/ShareBoth/yearly_variable_data/rasters/Vcomp_annual/Vcomp_annual/", full.names = TRUE)
length(Vcomplist)
V <- brick(Vcomplist)
wd <- (180/pi)*(atan2(U,V))
ws <- sqrt(U^2+V^2)
data link
https://drive.google.com/drive/folders/1PwABGUDBVUWi50Vfn9pmC-Dyjkpmtyny?usp=sharing
expected output:
thanks in advance

How to extract NetCDF data frame by region using a polygon shapefile

I'am trying to extract the variable "swh_ku" from multiple NetCDF files together with their corresponding latitude and longitude values into csv files using a polygon shapefile or it's extent. I'm working with Jason-1 global altimetry swath data but I only need the data for the domain represented by the shapefile. I just need help with some lines of code that would complete the working code bellow so I can extract only the data for the region I'm interested in.
I've tried several software applications such as QGIS, ESA SNAP, Broadview Radar Altimetry Toolbox (BRAT) with no success unfortunately because I couldn't find a way automate the extraction process for the hundreds of NetCDF files. So I resorted to code with which I'm fairly new but managed to get it working after reading other posts. I've tried opening the files as raster or brick to use the #extract or #mask functions because they seem more straightforward but I couldn't manage to work them out.
Link to data: https://drive.google.com/drive/folders/1d_XVYFe__-ynxbJNUwlyl74SPJi8GybR?usp=sharing
library(ncdf4)
library(rgdal)
library(raster)
my_read_function <- function(ncname) {
setwd("D:/Jason-1/cycle_030")
bs_shp=readOGR("D:/Black_Sea.shp")
e<-extent(bs_shp)
ncfname = ncname
names(ncin[['var']])
dname = "swh_ku"
ncin = nc_open(ncfname)
print(ncin)
vars<-(names(ncin[['var']]))
vars
lon <- ncvar_get(ncin, "lon")
nlon <- dim(lon)
head(lon)
lat <- ncvar_get(ncin, "lat", verbose = F)
nlat <- dim(lat)
head(lat)
print(c(nlon, nlat))
sm_array <- ncvar_get(ncin,dname)
dlname <- ncatt_get(ncin,dname,"long_name")
dunits <- ncatt_get(ncin,dname,"units")
fillvalue <- ncatt_get(ncin,dname,"_FillValue")
dim(sm_array)
ls()
sm.slice <- sm_array[]
sm.vec <- as.vector(sm.slice)
length(sm.vec)
lonlat <- expand.grid(lon, lat)
sm.df01 <- data.frame(cbind(lonlat, sm.vec))
names(sm.df01) <- c("lon", "lat", paste(dname, sep = "_"))
head(na.omit(sm.df01), 20)
csvfile <- paste0(ncname,".csv")
write.table(na.omit(sm.df01), csvfile, row.names = FALSE, sep = ",")
}
my_files <- list.files("D:/Jason-1/cycle_030/")
lapply(my_files, my_read_function)
Looks like your data is not gridded.
library(ncdf4)
library(raster)
bs <- shapefile("Black_Sea.shp")
# simplify so that the data will look better later
bs <- as(bs, "SpatialPolygons")
f <- list.files("cycle_022", pattern="nc$", full=TRUE)
Loop would start here
ncfname = f[1]
dname = "swh_ku"
ncin = nc_open(ncfname)
lon <- ncvar_get(ncin, "lon")
lat <- ncvar_get(ncin, "lat", verbose = F)
sm_array <- ncvar_get(ncin, dname)
xyz <- na.omit(cbind(lon, lat, sm_array))
p <- SpatialPoints(xyz[,1:2], proj4string=crs(bs))
p <- SpatialPointsDataFrame(p, data.frame(xyz))
x <- intersect(p, bs)
x has the points that intersect with the Black Sea
plot(bs)
points(x)
head(x#data)

Create plot from .ncdf data in R

I have a NetCDF file of salinity in Indonesia water with 4 dimension (lon, lat, depth and time). I would like to create a map from my data, but it's appear not in appropriate position that not exactly match with the coastline.
download data here: https://onedrive.live.com/redir?resid=6FFDD661570C7D0A%21177
output map here: https://onedrive.live.com/redir?resid=6FFDD661570C7D0A%21176
# This is my script
library (ncdf)
library (raster)
library (sp)
setwd ('D:/work')
bio <- open.ncdf('data.nc')
print (bio)
sal.dat <- get.var.ncdf(bio,"salinity")
sal0 <- brick(sal.dat[,,1,])
extent(sal0) <- c(105,110,-5,0)
projection(sal0) <- CRS("+proj=longlat +datum=WGS84")
#plot image
image (sal0)
# load coastal lines of Indonesia:
con <- url("http://biogeo.ucdavis.edu/data/gadm2/R/IDN_adm0.RData")
load(file = con)
close(con)
# plot coastal lines:
plot(gadm, add = T)
You can use rasterVis package for that purpose:
# load needed librairies
library(rasterVis)
library(rgeos)
# open the data
salinity <- brick("data.nc", varname = "salinity")
# load coastal lines of Indonesia:
con <- url("http://biogeo.ucdavis.edu/data/gadm2/R/IDN_adm0.RData")
load(file = con)
close(con)
# clip the coastline to the study area
CP <- as(extent(salinity), "SpatialPolygons")
proj4string(CP) <- CRS(proj4string(gadm))
gadm <- gIntersection(gadm, CP, byid=TRUE)
# map
levelplot(subset(salinity, 1), margin = FALSE) +
layer(sp.polygons(gadm, fill='transparent', col='black'))

Resources