[R-sig-Geo] randomly changing raster pixels

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Tue Jul 3 21:08:40 CEST 2012


On Tue, Jul 3, 2012 at 7:09 PM, Frederico Mestre
<mestre.frederico at gmail.com> wrote:
> Hello:
>
>
>
> I've got a raster generated with the raster package. I want to randomly
> change the value of  pixels of a given value.
>
>
>
> For example, I want to select 25% of the pixels with value 2, changing its
> value to 3.
>
>
>
> Any ideas?
>

 For some raster r, do a test for which cells are 2:

is2 = r==2

then set FALSE to NA:

is2[!is2]=NA

how many have you got?

sum(values(is2),na.rm=TRUE)
[1] 64

so we want to replace 16. use sampleRandom to return cell indices (it
doesnt return the NA cells, which is the reason for setting the NAs
above):

r[sampleRandom(is2,16,cells=TRUE)[,'cell']]=3

The r raster was originally approx 64 cells of values 1 to 4. Now it is:

 table(values(r))

 1  2  3  4
66 48 82 60

Looks about right...

Expect Robert in about a minute with a simpler solution!

Barry



More information about the R-sig-Geo mailing list