2020年12月20日星期日

How to pick random points greater than 0

I wish to extract values from a raster where all the XY coordinates are greater than 0 which match rpoints (randomly selected points) from another raster.

Here's my code:

df<-getValues(rf)  rpoints <- data.frame(xyFromCell(rf, 1:ncell(rf)),layer=getValues(rf))  rpoints <- subset(rpoints,!is.na(layer)) #limit to non-na points  rpoints$layer <- NULL #get rid of column to leave just points  dim(rpoints)    #randomly select 1000 points:  rpoints <- rpoints[sample(1:nrow(rpoints),10000,replace = F),]     #now extract data for bird encounter rate change and habitat change  # Example habitat change raster:  e_change <- raster::extract(rf, rpoints) #extract cell values for bird change  h_change <- raster::extract(habs,rpoints, fun=gg)#extract cell values for habitat change  

Here is a reproducible raster code:

#first set of code to create rf  library(raster)  set.seed(5000)  df <- data.frame( x = rep( 0:5000, each=2 ),                    y = rep( 0:5000,  2),                    l = rnorm( 10002 ))  spg <- df  coordinates(spg) <- ~ x + y  # coerce to SpatialPixelsDataFrame  gridded(spg) <- TRUE  # coerce to raster  rasterDF <- raster(spg)    rf <-  rasterDF  rf <- aggregate(two_1, fact=2)    #repeat code above to create habs    df <- data.frame( x = rep( 0:5000, each=2 ),                    y = rep( 0:5000,  2),                    l = rnorm( 10002 ))  spg <- df  coordinates(spg) <- ~ x + y  # coerce to SpatialPixelsDataFrame  gridded(spg) <- TRUE  # coerce to raster  rasterDF <- raster(spg)    habs <-  rasterDF  habs <- aggregate(two_2, fact=2)  

This does not match my dataset exactly, habs will have lots of zeros, so I only want to acquire those values where coordinates match both rf and habs where habs has values greater than zero.

I have tried:

h_change <- raster::extract(habs>0,rpoints, fun=gg)  

however, it does not give the intended output.

https://stackoverflow.com/questions/65387074/how-to-pick-random-points-greater-than-0 December 21, 2020 at 11:03AM

没有评论:

发表评论