I'm trying to plot a image (a flag) on a map using raster layers and
# Load packages
library(maptools)
library(raster)
library(jpeg)
# Read in a jpeg and convert to raster
usa.flag <- as.raster(readJPEG(".../usa.jpg"))
# Get spacial image of map
data("wrld_simpl")
usa.map <- subset(wrld_simpl, NAME == "United States")
When I try to crop, I get an error:
usa.sub <- crop(usa.flag, extent(usa.map))
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘crop’ for signature ‘"raster"’
But I can't figure out what I'm missing about the use of crop().
Related
I would like to mask a raster using all the polygons contained in a "SpatialPolygonsDataFrame" object.
Up until now i tried this:
r=raster("myraster.asc")
Then I got my SpatialPolygonsDataFrame (called "vor_spdf") object with a list of 6 Polygons, so I runned:
typeof(vor_spdf) # It results in [1] "S4"
r1=crop(r,extent(vor_spdf))
r2=mask(r1,vor_spdf#polygons[[1]]) #Trying to mask the raster on the geometry of the first polygon
This is the error... Error in (function (classes, fdef, mtable) : unable to find an inherited method for function ‘mask’ for signature ‘"RasterLayer", "Polygons"’
Do you have any suggestion on how to handle this?
Thank you
Example data
library(raster)
library(terra)
p <- shapefile(system.file("external/lux.shp", package="raster"))
r <- rast(system.file("ex/elev.tif", package="terra")) |> raster()
Solution
m <- mask(r, p[1,])
But you are using outdated packages. You might be better off using "terra" instead.
library(terra)
v <- vect(system.file("ex/lux.shp", package="terra"))
r <- rast(system.file("ex/elev.tif", package="terra"))
m <- mask(r, v[1,])
I'm trying to determine if a point falls within a JSON sf. There were several postings that indicated the "over" function in the "sp" package would work, but I'm getting an error.
northamerica <- geojsonsf::geojson_sf("data/custom.geo.json") #source: https://geojson-maps.ash.ms/ - Regions - north america
northamerica <- sf::st_transform(northamerica,crs=4326)
pts <- data.frame(click=1,lat=37.43997, lng=277.9102)
pts <- sf::st_as_sf(x = pts,coords = c("lng", "lat"),
crs = 4326)
sp::over(pts,northamerica)
I get the following error when I run the above code:
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘over’ for signature ‘"sf", "sf"’
Any ideas why I'm getting this error or suggestions on an alternative method?
I realized that with sf objects that I needed to us "sf_within" instead of "over" from the sp package. Still learning spatial data in R.
I am working on R and creating prediction maps. In my data, I have the location coordinates.
How to extract my rasters and points?
library(randomForest)
library(caret)
library(raster)
library(raster)
library(rgdal)
##-----load data
data <- read.csv("0.10.coordinates.csv",sep=";", header = TRUE)
raster(swi.tif)
rsp.1<-raster("rsp.tif")
twi.1<-raster("twi.tif")
swi.1<-raster("swi.tif")
###load csv of 0-10cm sand,silt and clay %'s and lat/long (x,y) (in E: drive RF folder)
xy<-read.csv("0.10.coordinates.csv")
plot(swi.1)
plot(twi.1)
plot(swi.1)
plot(rsp.1)
stack(swi.1,rsp.1,twi.1,xy)
topo.brick<-brick(rsp.1,swi.1,twi.1,xy)
brick(rsp.1,twi.1,swi.1,data)
df<-extract(data,rsp.1,twi.1,swi.1)`
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘extract’ for signature ‘"data.frame", "RasterLayer"’
take a look at?raster::extract to see what inputs are required and in what order. In any case, you should create a reproducible example..
However, here an example with dummy data:
library(raster)
# with raster -------------------------------------------------------------
r <- s <- t <- raster()
r[] <- 1:ncell(r)
s[] <- sample(1:10,ncell(s),replace = T)
t[] <- runif(ncell(t))
stacked <- stack(r,s,t)
#points
xy <- cbind(-50, seq(-80, 80, by=20))
#extract
ex <- extract(stacked,xy, df=TRUE)
If the extraction takes too long, check out the terra::extract or even better a exactextractr::exact_extract.
See Elia's example, but from what I gather from your code you should be able to do
library(raster)
xy <- read.csv("0.10.coordinates.csv")
s <- stack("rsp.tif", "twi.tif", "swi.tif")
d <- extract(s, xy)`
I want to extract world climate data for minimum and maximum temperature for only one country India using R and save it as a data set (to use with my own data-set that contains crop yields at the district level).
I have gone through several posts and can see that this can be done easily in R, however the posts that I have tried to follow are a bit different in terms of the commands or sequences and I am getting confused.
(https://gis.stackexchange.com/questions/259478/worldclim-data-na-for-my-coordinates, https://gis.stackexchange.com/questions/227585/using-r-to-extract-data-from-worldclim
What I have tried to use is as follows.
library(raster)
library(sp)
r<- getData('CMIP5', var='tmin', res=10, rcp=45, model='HE', year=70)
r <- r[[c(1,12)]]
values <- extract(r,points)
df <- cbind.data.frame(coordinates(points),values)
head(df)
However, I can run only the first two lines and the line values
<- extract(r,points) gives the error Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘extract’ for signature ‘"RasterStack", "function"’
Any suggestions?
Here is the solution for it
library(raster)
library(sp)
library(rgeos)
library(rgdal)
library(sf)
r<- getData('CMIP5', var='tmin', res=10, rcp=45, model='HE', year=70)
#Using Zonal statistics
poly <- shapefile("Provide_your_drive_name" e.g. "F:\\Kriging in R\\India Shape files\\2011_Dist.shp")
plot(poly)
#This will take considerable time
ex <- extract(r, poly, fun='mean', na.rm=TRUE, df=TRUE, weights = TRUE)
write.csv(cbind(poly$DISTRICT,ex),"Worldclim.csv", row.names = F)
# using centroids
nc <- st_read(dsn="Provide_your_drive_name" e.g. "F:\\Kriging in R\\India Shape files", layer="2011_Dist")
# just view the attributes & first 6 attribute values of the data
head(nc)
sp_cent <- gCentroid(as(nc, "Spatial"), byid = TRUE)
values <- extract(r,sp_cent)
write.csv(cbind(as.data.frame(nc$DISTRICT),as.data.frame(values)),"Worldclim_centroids.csv", row.names = F)
I have netcdf files of daily temperature and precipitation data
How is it possible to Change projection of a netcdf?
I have tried to doing this using raster function to read the files
and reproject them with projectraster?
Code_used
a <-raster(file.nc)
cr1<-"+proj=longlat +datum=NAD83 +no_defs+ellps=GRS80 +towgs84=0,0,0"
projectRaster(a, cr1,res = 0.04166667)
ERROR_
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘res’ for signature ‘"character"’
In addition: Warning message:
In min(dim(to)[1:2]) : no non-missing arguments to min; returning Inf
The help for projectRaster gives this usage:
Usage:
projectRaster(from, to, res, crs, method="bilinear",
alignOnly=FALSE, over=FALSE, filename="", ...)
if you call it with two unnamed arguments, they get matched to from and to, and to is:
to: Raster* object with the parameters to which 'from' should be
projected
if instead you name the second argument, this should work:
a_project = projectRaster(a, crs = cr1, res = 0.04166667)
because now the second argument is matched as the crs argument.
BUT if you just want to transform a gdal-compatible data set then you can use gdaltransform, either from the command line or via the function with the same name from the gdalUtils package.