New answers tagged

1 vote
Accepted

Ordinary Kriging: "Warning message: In fit.variogram(data.var, vgm("Mat")) : No convergence after 200 iterations: try different initial values?"

The code is struggling to find well-defined parameter estimates for the model. This is often a sign that the model is maybe over-defined (too many parameters) for the data it is fitting. Variograms ...
user avatar
  • 51.2k
3 votes

Clipping dataframe (spatial data) to area of interest using R

I would recommend modernizing your workflow a bit. The depreciation schedule for sp and rgdal have been announced, being replaced by sf. The terra library is the replacement for raster, with much of ...
user avatar
1 vote

R Terra: Write multiple time series variables to NetCDF

A SpatRasterDataset does not have a time dimension. The SpatRasters it contains can have that dimension, and it may be different for each SpatRaster. Here is a simplified script that suggests that all ...
user avatar
2 votes

Clipping dataframe (spatial data) to area of interest using R

To clip a dataframe with spatial info to a desired study area: (1) Convert the dataframe to a spatialpointdataframe by assigning spatial info. # where your dataframe has the following columns: # Lat, ...
user avatar
0 votes

Enlarging gBuffer width changes polygon shape

The gBuffer function needed a joinStyle = "MITRE" argument.
user avatar
  • 9
0 votes
Accepted

Applying Moran's I across columns

As a possible alternative to the approach suggested by Spacedman I propose one based on {dplyr} and iterating via a for cycle over a vector of names of your variables of interest. As I don't have ...
user avatar
2 votes

Applying Moran's I across columns

Make a vector of your variable names either by subsetting the column names or programmatically, eg: vars = names(data_lisa)[2:5] vars = paste0("var_",letters[1:4]) For an example, I'm using ...
user avatar
  • 51.2k
2 votes
Accepted

Creating regular sampling grid, with specific distance between points using R

I would create a SpatRaster using the SpatVector as template, and set the resolution to 10 meters. Then you got a Raster with the desired gap that you can transform to points if needed. On this ...
user avatar
4 votes

QGIS reads blank cells as "nan" instead of "NULL"

I wouldn't be able to help with sorting this in R, however regarding the post-processing in QGIS, you current request in the field calculator is: if("field" = "nan", NULL, "...
user avatar
  • 156
0 votes

Downloading CHIRPS data sets using R

Here an example using the R package chirps. You can also change the data provider using the argument server. ClimateSERV takes the data from SERVIR Global, which I recommend when you have few data ...
user avatar
0 votes

Spillover Binary variable based on neighboring cell in R

Since it seems that you started out with raster data let's go back to that: library(terra) r = rast(px[, c("xcoord", "ycoord", "gid")]) |> extend(2) f = focal(r, 3, ...
user avatar
3 votes
Accepted

Which point lies on which linestring?

Use st_intersects which returns a list for each point of which features the point is on. EG the nc data cast to linear features: > nc Simple feature collection with 100 features and 14 fields ...
user avatar
  • 51.2k
0 votes

Soilgrids points outside of projection domain

Perhaps this is because the extent of your template raster is a bit off: -180.0001, 179.9999, -90.00014, 83.99986 (xmin, xmax, ymin, ymax) Now, -180.0001 is not wrong (it is the same as 179.9999) but ...
user avatar
1 vote
Accepted

How to export result of point_metrics() in lidR?

There are plenty of options depending on what you really want to do. You can keep only the points with min Z that way library(lidR) f = system.file("extdata", "Topography.laz", ...
user avatar
  • 7,364
1 vote

'union' between spatial polygons and spatial points in R

I found out how to do it. Two ways: applying point.in.poly(grid, acled). So x= polygons, y=points. applying point.in.poly(ACLED, grid) in the right way then merging with the initial grid. grid....
user avatar
  • 41
1 vote

Calculate sum/average of variable within each group of neighboring counties using R

I had this exact issue a few months ago working on a project and ended up developing a package to do just that. I just now published the package on GitHub and can be installed in R by running devtools:...
user avatar
  • 11
0 votes

Write layer style .qml as predefined within a gpkg using R

Thanks to @Spacedman I manage to do so by : -in Qgis(3.2) save your style in database (Geopackage) and export as .gpkg in R : #I save my style layer as an object mystyle <- sf::st_read("...
user avatar
0 votes

Check for NAs in `RasterLayer` and plot them in different colour

Example data f <- system.file("ex/elev.tif", package="terra") r <- rast(f) Count the cells that are NA (1, TRUE) or not-NA (0, FALSE) freq(is.na(r)) layer value count [...
user avatar
0 votes

R - gdistance: setting to 0 the conductance values of cells corresponding to a polyline

Transform your first AtoB path into a 0/1 raster, invert the values and create a new raster with 0 values on that path. > library(spatialEco) > r2 <- rasterize(AtoB,r,background=0) > r2 &...
user avatar
  • 389
0 votes
Accepted

R stars read_ncdf returns "vector memory exhausted (limit reached?)" when proxy = TRUE

Answer thanks to comments from @Spacedman The current version of stars on CRAN does not include the option to set proxy = TRUE for read_ncdf(). This was included in the latest update to 0.5.6 Update ...
user avatar
1 vote

grid_canopy() fails when chunk has 1 veg return

A good work around is the one provided by JRR in the comments. if (npoints(vegetation) < 3) return(NULL) This is because it's not the single return that's causing the problem, but the fact that the ...
user avatar
  • 427
0 votes

Converting points to latitude and longitude values in R

I've used the following code to make a test raster that prints like yours (but is about 1/100000000 of the size): testlat = raster(matrix(1:100,10,10)) extent(testlat) = c(xmin=13000,xmax=278000,ymin=...
user avatar
  • 51.2k
4 votes
Accepted

How to treat NAs using a custom function in the lapp function of {terra} in R

As @Spacedman says, a vectorized solution should work this function should give you the expected result. t <- lapp(c(r,s), fun = function(a,b){ a[is.na(a)] <- 55 ...
user avatar
2 votes

How to treat NAs using a custom function in the lapp function of {terra} in R

This from the docs: Before you use the function, test it to make sure that it is vectorized. That is, it should work for vectors longer than one, not only for single numbers. Let's test: > fun(...
user avatar
  • 51.2k
3 votes
Accepted

Extracting mean of multiple SpatRasters using Terra?

The terra equivalent of raster::calc is terra::app so, to return the mean for a multi-band raster you would use: rmean <- app(x, mean) or to return the mean for an entire raster: global(x, mean).
user avatar
0 votes
Accepted

Ripley's K function and toroidal shift with Splancs

Yup. The code takes the bounding box of your polygon window and uses that. Yup points will get shifted out of the window. Quite how that breaks things I'm not sure, but splancs never was much for ...
user avatar
  • 51.2k
1 vote
Accepted

Read geo-spatial data in R via Leaflet

Here's a sample sp-class points data frame in a projected coordinate system like your data is: > ps class : SpatialPointsDataFrame features : 4 extent : 1, 4, 1, 4 (xmin, xmax, ...
user avatar
  • 51.2k
0 votes

Apply linear stretch to Landsat 8 images in the tmap R package

I figured out how to improve the contrast: fcc_nir_s <- terra::stretch(fcc_nir, minv = 0, maxv = 255, minq = 0.2, maxq = 0.98) tm_shape(fcc_nir_s) + tm_rgb() This rescales rasters to 8-bit and ...
user avatar
  • 103
0 votes
Accepted

Count multilinestring elements crossing a raster cell in R

Following @JeffreyEvans suggestion, I achieved it using an "extract" approach: First, I assigned an unique ID to each raster pixel: values(rast.w) <- 1:ncell(rast.w) Then, I used the ...
user avatar
  • 75
0 votes

Apply linear stretch to Landsat 8 images in the tmap R package

Linear stretch with stretch="lin" in plotRGB will stretch up to the max of your data, which is 23358. If you do: tmap(fcc_nir) + tm_rgb(max.value = max(values(fcc_nir))) then you should ...
user avatar
  • 51.2k
1 vote

Convert rworldMap to UTM

This does not change the numbers in the data, it only sets the coordinate system metadata: > projection(map.cp.utm) <- CRS(proj4string(CP.utm)) see how the extent is still in degrees: > map....
user avatar
  • 51.2k
0 votes

Error message with Krige function: Error in as.character.default(X[[i]], ...) : no method for coercing this S4 class to a vector

I figured it out. It looks like I had duplicate coordinate points in my data. Once I removed the duplicates it worked for me.
user avatar
  • 1
0 votes

Reprojecting a raster from long/lat to UTM take 2

Use projectRaster function with crs argument. You can also use terra since it's faster and projection takes a lot of time. But with raster library: r3utm <- projectRaster(from = r3, crs = "+...
user avatar
  • 11.8k
0 votes

projectRaster on a list of rasters

You are reprojecting to the last raster's CRS. It's a bit confusing, I recommend you to: Project to a known CRS (it could be stored in an object as well) Use a raster as template Also, since this ...
user avatar
  • 11.8k
1 vote

using function inside raster::calc with loop

I would use lag function from dplyr package: Your data: library(raster) r1 <- raster(nrows = 1, ncols = 1, res = 0.5, xmn = -1.5, xmx = 1.5, ymn = -1.5, ymx = 1.5, vals = 0.3) rr <- lapply(1:12, ...
user avatar
  • 11.8k
1 vote
Accepted

Create sf polygon from sf linestring and bounding box

I suggest using lwgeom::st_split() to split your counties object according to the coast linestring. It will return a geometry collection, so it needs to be piped to a sf::st_collection_extract("...
user avatar
2 votes

How can I make a raster layer where each pixel is a value representing the minimum distance between that pixel and a value from another layer?

Use "Proximity (raster distance)": Black is short distance, white is longer
user avatar
  • 51.4k
2 votes
Accepted

Unexpected resolutions when aggregating rasters with raster package in R

aggregate function decreases resolution x times according to fact. Since it's x times, fact is a positive integer. This is stated in description: fact postive integer. Aggregation factor expressed as ...
user avatar
  • 11.8k
2 votes
Accepted

How to compute partial correlation of pixels in R

Lets first make some test data: sos = rast(array(runif(10*10*20),c(10,10,20))) tem = rast(array(runif(10*10*20),c(10,10,20))) pre = rast(array(runif(10*10*20),c(10,10,20))) NDVI = rast(array(runif(...
user avatar
  • 51.2k
0 votes

R lm.LMtests error in lag.listw(listw, y, zero.policy) : y not numeric

Changing the dependent variable's class from character to numeric resolved the problem. fires_OGR$FIRE = as.numeric(fires_OGR$FIRE)
user avatar
1 vote
Accepted

Coloring polygons (made with concaveman) in ggplot by column

I recommend you to use fortify function getting a data.frame. Then you can easily add any other kind of variable adding a new column: concave.spdf2 <- fortify(concave.spdf) concave.spdf2 <- ...
user avatar
  • 11.8k
1 vote

R Distance from Point to Line: Negative if within shape

Outine solution: Cast the polygons to lines using st_cast and compute distances of pounts to lines (otherwise you get zero for the distance of points inside polygons). Use st_intersects on the ...
user avatar
  • 51.2k
0 votes

R Markdown Knitting Produces Garbage

You need to set up the chunk. You can deactivate the code call with echo, warning messages and any other kind of message (Use also fig.cap, fig.height, fig.width and fig.align for plot customization): ...
user avatar
  • 11.8k
0 votes

How can I get the correct mean from focal() with a circular window?

A somewhat simpler function (but perhaps no faster, though I haven't checked) using raster is to first convert the focal weights matrix to 1s and NAs, then (using focal) multiply the window (x) by ...
user avatar
1 vote

How to iterate erasing multiple vectors from another vector using R?

I would read your 10 shapefiles into a list object so that you can easily combine them using do.call. s <- do.call("rbind", lapply(list.files(getwd(), "shp$")[-1], st_read)) ...
user avatar
3 votes

Formatting decimal point for X,Y coordinates using R

The data is in latitude, longitude order, you are assigning them in the wrong order. According to the metadata on the page you linked to: Latitude = non-decimal latitude. Please use this formula to ...
user avatar
  • 51.8k
6 votes
Accepted

Anonymize site locations

There's a function in the maptools package called elide that is designed to shift and rotate spatial data. It can also flip, reflect, and rotate vector data, but it might be hard to do the equivalent ...
user avatar
  • 51.2k

Top 50 recent answers are included