dataframe - Extracting pixels from a raster based on specific value of another raster using R -


i imported 2 rasters (raster a , b)in r using raster function. extract pixels of a b equals 1 data frame. trying following, however, pixels obtain have same values, although various in original dataset.

the 2 rasters have same dimensions (ncols, nrows, ncell, resolution, extent, projection).

library(raster) library(rgdal)  # import inputs <- raster('/pat/to/rastera.tif') b <- raster('/pat/to/rasterb.tif')  # extract raster values on raster b b == 1 mydata <- data.frame(a[b[b == 1]]) 

edit 1

might when a[b[b == 1]], class of object , b rasterlayer becomes numeric, , creates problems? discovered doing class(a[b[b == 1]]), gives numeric.

edit 2

ok, weird. tried mydata <- data.frame(a[b]) , output has original a @ b == 1 locations. trying before extracted pixels a (as expect). can coinfirm right counting number of ones in b , number of elements in mydata, same. it's if indexing has skipped zeros in b. can explain this?

please include example data in questions this:

library(raster) r <- raster(nrow=5, ncol=5, xmn=0, xmx=1, ymn=0, ymx=1) set.seed(1010) <- setvalues(r, sample(0:5, ncell(r), replace=true)) b <- setvalues(r, sample(0:2, ncell(r), replace=true)) 

now can do:

s <- stack(a,b) v <- as.data.frame(s) v[v[,2] == 1, 1] 

alternatively

a[b==1] 

or

d <- overlay(a, b, fun=function(x,y){ x[y!=0] <- na; x}) na.omit(values(d)) 

or

xy <- rastertopoints(b, function(x) x == 1) extract(a, xy[,1:2]) 

or

a[b!=1] <- na rastertopoints(a)[, 3] 

etc...

now why this: a[b[b == 1]] not work? unpack it:

b[b == 1] # [1] 1 1 1 1 1 1 1 1 1 1 

the cell values of b b==1 are, of course, 1. a[b[b == 1]] becomes a[c(1,1,1,..)], , returns value of first cell many times.

a[b] equivalent a[b!=0] b considered logical statement in case, , 0 == false , other values true


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -