'st_intersects' applied to an object of class "data.frame" - r

I am trying to convert latitude/longitude to Census Tract or FIPS using R studio. I am getting the following error message when I am running "system.time"
"Error in UseMethod("st_intersects") :
no applicable method for 'st_intersects' applied to an object of class "data.frame"
Timing stopped at: 0 0 0"
Entire Code:
library(sf)
list.files("./tl_2010_22_tract10")
census_tracts <- st_read("./tl_2010_22_tract10/tl_2010_22_tract10.shp")
head(census_tracts)
library(readxl)
DAT <- read_excel("~/DAT.xlsx")
View(DAT)
latlong_dat = data.frame(DAT)
latlong_sf <- latlong_dat
filter(!is.na(LAT), !is.na(LONG))
st_as_sf(latlong_dat, coords = c("LONG", "LAT"), crs =
st_crs(census_tracts))
head(latlong_dat)
system.time({intersected <- st_intersects(latlong_sf, census_tracts)})
Screenshot of code
DAT FILE

Related

R warning messages: 1: In proj4string(x) : CRS object has comment, > which is lost in output; in tests, see

I am fairly new to R and am trying to run a home range analysis, but I'm running into the below warning message:
> Warning messages: 1: In proj4string(x) : CRS object has comment,
> which is lost in output; in tests, see
> https://cran.r-project.org/web/packages/sp/vignettes/CRS_warnings.html
I don't seem to be able to follow any of the answers provided and am hoping someone here will be able to explain to me what this warning message means and what I need to do to not get this warning.
I am running a home range analysis using LSCV with the code below:
LSCVdata <- kernelUD(sp.UTMdata, h = 'LSCV', grid = 800, extent = 2.2)
LSCVdata50 <- getverticeshr(LSCVdata, 50, unin = "m", unout = "km2")
LSCVdata95 <- getverticeshr(LSCVdata, 95, unin = "m", unout = "km2")
LSCVdata99 <- getverticeshr(LSCVdata, 99, unin = "m", unout = "km2")
The packages and libraries installed include:
library(move)
library(adehabitatHR)
library(caTools)
library(spatialEco)
library(reshape2)
library(sf)
library(ggplot2)
library(dplyr)
library(lubridate)
library(mapview)
library(cowplot)
library(ggspatial)
Data layout is: ("Animal ID", "Longitude", "Latitude", "date")
Any help and pointers here would be greatly appreciated.
Thanks!

Unable to project simple features or change projection

I am trying to convert a csv to an sf spatial data file, however I'm getting errors that I cant' figure out.
Example:
library(tidyverse)
library(sf)
#> Linking to GEOS 3.8.0, GDAL 3.0.4, PROJ 6.3.1
point_df <- tibble::tribble(
~city_name, ~longitude, ~latitude,
"Akron", -81.5190053, 41.0814447,
"Albany", -73.7562317, 42.6525793,
"Schenectady", -73.9395687, 42.8142432,
"Albuquerque", -106.650422, 35.0843859,
"Allentown", -75.4714098, 40.6022939,
"Bethlehem", -75.3704579, 40.6259316,
"Atlanta", -84.3879824, 33.7489954,
"Augusta", -82.0105148, 33.4734978,
"Austin", -97.7430608, 30.267153,
"Bakersfield", -119.0187125, 35.3732921
)
point_sf <- st_as_sf(point_df, coords = c("longitude", "latitude"))
point_sf <- st_set_crs(point_sf, 4326)
st_transform(point_sf, 102003)
#> Warning in CPL_crs_from_input(x): GDAL Error 1: PROJ: proj_create_from_database:
#> crs not found
#> Error in CPL_transform(x, crs, aoi, pipeline, reverse): crs not found: is it missing?
Any help would be greatly appreciated.
EDIT
I found a kludgy solution which I adapted from this github page, but I am stil looking for a more systematic solution if possible. https://github.com/r-spatial/sf/issues/1419
The solution here is to convert the sf object into sp then change back to sf.
reProject <- function (sf, proj_in = "+init=epsg:4326",
proj_out = "+proj=aea +lat_1=20 +lat_2=60 +lat_0=40 +lon_0=-96 +x_0=0 +y_0=0 +datum=NAD83 +units=m +no_defs") {
require(sp)
data_sp <- as(sf, "Spatial")
proj4string(data_sp) <- CRS(proj_in)
sf_out <- st_as_sf(spTransform(data_sp, CRS(proj_out)))
}
dat_out <- reProject(point_sf)
It appears something was expected to happen with the following line of code. But that something is not happening.
point_sf <- st_as_sf(point_df, coords = c("longitude", "latitude"))
While this line of code creates the simple feature geometric point objects, this code does not create the simple feature geometry column (sfc) object. And since there is no sfc object, the next line of code does not work.
point_sf <- st_set_crs(point_sf, 4326)
In this other line of code, the function, st_set_crs(), retrieves a coordinate reference system from sf or sfc objects. But neither the sf or the sfc objects currently exist.
Therefore, the sfc object must be first created before using the function: st_set_crs().
It really helps to follow the following steps whenever doing these types of simple feature projects.
x.sfg <- st_multipoint(c(lon,lat), dim = "XY") # create sf geometry from lon/lat
x.sfc <- st_sfc(x.sfg, crs = 4326) # create sfc from geometry
x.sf <- st_sf(df, x.sfc) # create sf object from sfc
First convert the log and lat to vectors, then create the matrix, and then create the simple feature objects in the correct progression.
lon <- c(-81.5190053, -73.7562317, -73.9395687, -106.650422, -75.4714098, -75.3704579, -84.3879824, -82.0105148, -97.7430608, -119.0187125)
lat <- c(41.0814447, 42.6525793, 42.8142432, 35.0843859, 40.6022939, 40.6259316, 33.7489954, 33.4734978, 30.267153, 35.3732921)
m <- matrix(data = c(lon, lat), nrow = 10, ncol = 2, byrow = FALSE)
m.sfg <- st_multipoint(m, dim = "XY")
m.sfc <- st_sfc(m.sfg, crs = 4326)
m.sf <- st_sf(df, m.sfc)
head(m.sf, 3)
Then create a base plot of the continental US, and then plot the simple feature object onto the base map.
plot(US_48, axes = TRUE)
plot(m.sf, add= TRUE, pch = 19, col = "red")
The link shown above with the question does not seem to have anything related to this question. The answer shown here does not convert the sf object into sp then change back to sf.
The plot is shown at link:

Error in rgeos::createPolygonsComment(oobj) : orphaned hole using geojsonio in R

Im am trying to create a .geojson file in my local repository for this output. I am downloading the file locally, making my adjustments and writing input21.geojson, however, I get the message:
Error in rgeos::createPolygonsComment(oobj) :
rgeos_PolyCreateComment: orphaned hole, cannot find containing polygon for hole at index 51
My code so far:
library(jsonlite)
library(rgdal)
library(downloader)
library(geojsonio)
library(maptools)
u <- paste0('https://servicodados.ibge.gov.br/api/v2/malhas/21?formato=application/vnd.geo+json')
downloader::download(url = u, destfile = "/tmp/gas.GeoJSON")
gas <- readOGR(dsn = "/tmp/gas.GeoJSON")
gas$var0031 <- 21
gas$var0517 <- 0
gas$var0514 <- as.numeric(substr(as.character(gas$var0031),1,1))
gas$var0512 <- "MA"
gas$var0513 <- "Maranhão"
gas <- gas[which(names(gas) %in% c("var0517", "var0031", "var0514", "var0512", "var0513"))]
geojsonio::geojson_write(gas, file = paste0("./data/in/sidra_malhas/input21.geojson"))
I Have figured a package called cleangeo that corrects some issues related with geo structure, adding the lines solve the problem:
gas <- cleangeo::clgeo_Clean(gas)
slot(gas, "polygons") <- lapply(slot(gas, "polygons"), checkPolygonsHoles)
before the line:
geojsonio::geojson_write(gas, file = paste0("./data/in/sidra_malhas/input21.geojson"))

Masking raster from data in SpatialGridDataFrame and SpatialPolygonsDataFrame

I am trying to mask a raster file by including only some specific area (‘Koeppen Geiger’ climatic zones) with several locations. I got an error message running the final line of code:
Error in (function (classes, fdef, mtable) : unable to find an
inherited method for function ‘mask’ for signature
‘"SpatialGridDataFrame", "SpatialPolygonsDataFrame"’
.
##Read Countries file
library(sp)
library(maptools)
library(rworldmap)
countries = readShapeSpatial("D:/Studies/PhD/SCI/modeling/ne_10m_admin_0_countries/ne_10m_admin_0_countries.shp") [enter link description here][1]
asia.zone = countries[countries$ADMIN=="South Korea"|
countries$ADMIN=="North Korea"|
countries$ADMIN=="Japan"|
countries$ADMIN=="China"|
countries$ADMIN=="Taiwan",]
##Read Koeppen Geiger’ climatic zones
tst <- read.csv('D:/Studies/PhD/SCI/modeling/Koeppen-Geiger-ASCII.csv',as.is=TRUE) [enter link description here][1]
tst.l <- tst [tst$Cls=="Cfc"|
tst$Cls=="Cfa"|
tst$Cls=="Cfb"|
tst$Cls=="Cwa"|
tst$Cls=="Cwb"|
tst$Cls=="Aw"|
tst$Cls=="As"|
tst$Cls=="Am"|
tst$Cls=="Dwd"|
tst$Cls=="Dwb"|
tst$Cls=="Dwa"|
tst$Cls=="Dwc",]
#convert to sp SpatialPointsDataFrame
coordinates(tst.l) = c("Lon", "Lat")
# promote to SpatialPixelsDataFrame
gridded(tst.l) <- TRUE
# promote to SpatialGridDataFrame
tst.lsGDF = as(tst.l, "SpatialGridDataFrame")
# mask the specific climate zone from some locations
asia.zone2 <- mask(tst.lsGDF,asia.zone)
If you look up ?mask you will see that it has been implemented for Raster* objects, not for SpatialGridDataFrame objects. So you need to coerce your data to a Raster object. Something like this might work:
library(raster)
setwd("D:/Studies/PhD/SCI/modeling/")
countries <- shapefile("vne_10m_admin_0_countries/ne_10m_admin_0_countries.shp")
asia.zone <- countries[countries$ADMIN %in% c("South Korea", "North Korea","Japan", "China", "Taiwan"), ]
tst <- read.csv("Koeppen-Geiger-ASCII.csv", stringsAsFactor=FALSE)
tst.l <- tst [tst$Cls %in% c("Cfc", "Cfa", "Cfb", "Cwa", "Cwb", "Aw", "As", "Am", "Dwd", "Dwb", "Dwa", "Dwc"),]
coordinates(tst.l) = c("Lon", "Lat")
# promote to SpatialPixelsDataFrame
gridded(tst.l) <- TRUE
r <- raster(tst.l)
asia.zone2 <- mask(r, asia.zone)

Minimum elevation within km

Trying to find the minimum elevation within 10km of a certain latitude and longitude using R.
So far I have
dem <- getData("SRTM", lat=42.90, lon=-78.85, path = datadir)
plot(dem)
I know I need to create spatial points and eventually buffer/extract the information.
When I try:
buffdem <- buffer(dem, width=10000)
It does not work because I don't have any points.
I tried
dem <- getData("SRTM", lat=42.90, lon=-78.85, path = datadir)
coords <- data.frame(
x = rnorm(100),
y = rnorm(100)
)
coordinates(dem)
spdf = SpatialPointsDataFrame(coords, dem)
I get the following error:
Error in validObject(.Object) : invalid class
“SpatialPointsDataFrame” object: invalid object for slot "data" in
class "SpatialPointsDataFrame": got class "RasterLayer", should be or
extend class "data.frame"
I think this accomplishes what you need:
library(raster)
#elevation <- getData("SRTM", lat=42.90, lon=-78.85)
#poi <- cbind(lon=-78.85, lat=42.90)
using a smaller example data set for quicker download:
elevation <- getData('alt', country='CHE')
poi <- cbind(8.13, 46.47)
e <- extract(elevation, poi, buffer=10000)
sapply(e, min, na.rm=TRUE)
By the way, this is a duplicate of this and this question.

Resources