[R-sig-Geo] select cells in a raster and change the values to 1

Jedrzej Bojanowski jedrzej.bojanowski at jrc.ec.europa.eu
Mon Mar 19 16:40:37 CET 2012


If I got your question well,

for the raster
r <- raster(matrix(rep(c(1:10),10),10,10))
and vector
v <- c(1:3)

You can change to 1 all the values of raster equal to the elements of vector
v with:

r[r%in%c(1,2,3)] <- 1

and then, everything else to NA with:

r[!r%in%c(1)] <- NA

HTH,

jed

_______________________________

Jedrzej Stanislaw BOJANOWSKI



European Commission
Joint Research Centre 
Institute for Environment and Sustainability
Monitoring Agricultural Resources Unit - H04
Crop Production Forecast and Climate Change Impact

Via Fermi 2749,
I-21027 ISPRA (VA), ITALY
+39.0332.78.5030 
jedrzej.bojanowski at jrc.ec.europa.eu
http://mars.jrc.ec.europa.eu/mars
jbojanowski.pl


> -----Original Message-----
> From: r-sig-geo-bounces at r-project.org [mailto:r-sig-geo-bounces at r-
> project.org] On Behalf Of Daisy Englert Duursma
> Sent: 19 March, 2012 11:53 AM
> To: r-sig-geo at r-project.org
> Subject: [R-sig-Geo] select cells in a raster and change the values to
> 1
> 
> Greetings,
> 
> I have a vector of values and I want to select cells in a raster that
> have these values, change these cells so they have a value of 1 and the
> rest of the raster will have a NA value.
> 
> library(raster)
> 
> #my example raster
> r <- raster(ncol=3, nrow=3)
> r[] <- 1:ncell(r)
> #a vector of cells I want to select
> vals<-c(2,4,6)
> 
> #I want to select cells with the values 2,4,6 a silly way to do it:
> r1<-r==2
> r2<-r==4
> r3<-r==6
> #make the final desired raster
> r4<-r1+r2+r3
> plot(r4)
> 
> #I have played around with a lot of differnt things but I think I want
> to use the funcion sub ######this does not work###### df =
> data.frame(id=c(2,4,6), v=c(1,1,1)) x = subs(r, df)
> 
> 
> 
> Is there a better way to do this? There must be a better way. What have
> I missed? I need to be able to select raster cells from a vector.
> 
> Thank you for your time and help,
> Daisy
> 
> 
> --
> Daisy Englert Duursma
> Department of Biological Sciences
> Room E8C156
> Macquarie University, North Ryde, NSW 2109 Australia
> 
> Tel +61 2 9850 9256
> 
> 	[[alternative HTML version deleted]]
> 
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo



More information about the R-sig-Geo mailing list