title: Change raster values using spatial polygons
body: <p>To change raster values under <code>SpatialPoints</code> you can simply use <code>[</code> . </p>
  
  <pre><code>r &lt;- raster(system.file("external/test.grd", package="raster"))
  rTp &lt;- rasterToPoints(r, spatial = T)
  
  set.seed(666)
  rTpS &lt;- rTp[sample(1:length(rTp), 500),]
  plot(r)
  plot(rTpS, add = TRUE, pch = ".")
  </code></pre>
  
  <p>Now, the raster values beneath the spatial points are changed like this: </p>
  
  <pre><code>r1 &lt;- r
  r1[rTpS] &lt;- 99999
  plot(r1)
  </code></pre>
  
  <p><strong>Raster with SpatialPoints (left) and raster with changed values (right):</strong>
  <a href="https://i.stack.imgur.com/5ZERp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5ZERp.png" alt="Raster with SpatialPoints (left) and raster with changed values (right)"></a></p>
  
  <p>Thus, I assumed that polygons work the same way. Therefore generate some polygons from this raster data set:</p>
  
  <pre><code>rst &lt;- as.integer(stretch(r, 0, 10))
  rTpol &lt;- rasterToPolygons(rst, dissolve = T)
  rTpol &lt;- rTpol[rTpol$layer &gt; 3,]
  
  plot(r)
  plot(rTpol, add = T)
  
  rst[rTpol[,]] &lt;- 100
  plot(rst)
  
  # also tried 
  # rst[rTpol] &lt;- 100
  </code></pre>
  
  <p>However, when i Try to change the raster values below some <code>SpatialPolygons</code>, somehow the ID (or something) of the polygons. Yet, it should be 100. </p>
  
  <p><strong>Raster with SpatialPolygons (left) and raster with strangely changed values (right):</strong> 
  <a href="https://i.stack.imgur.com/Hz7BZ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Hz7BZ.png" alt="Raster with SpatialPolygons (left) and raster with strangely changed values (right)"></a></p>
  
  <p>Therefore, my question is how to change raster values within polygons. </p>