AntonyDW
AntonyDW

Reputation: 349

How to move a cell value of a raster to another target cell using R

I have a raster, lets imagine it is 3*3 for now (although it is actually a lot bigger). Each of the raster cells has a value, a different value - i.e. a different Z value. I know the cell numbers of each cell within the raster (i.e. they are cell numbers 1 to 9 with 1 to 3 along the top row, 4 to 6 along the middle row and 7 to 9 along the bottom row.

I also have another raster with the 'target' cell number for each cell - lets say for example that the target cell for cell numbers 1,2,3,4,7,8,9 is 5 (i.e. the target cell is the middle cell for all cells except for 5 and 6), and the target cell for cell 5, is cell 6 and cell 6 does not have a target cell.

So what I want to do is write code that moves the Z value of the original raster into the specific target cells according to the target raster. In fact, cell 5 should be a sum of all the other feed cells. Any ideas? I've played a little with 'extract' and 'setValues'- and 'adjacent' but just can't get it right.

Any help would be greatly appreciated

Antony

For example this raster has the Z values:

20 24 22
18 34 26
21 24 32

So, the cell numbers would look like this:

1 2 3
4 5 6
7 8 9

and the target raster would look like this:

5 5 5
5 6 Out
5 5 5

and the code would produce an output raster after moving the cell values:

0 0 0
0 161 34
0 0 0

On the second iteration the raster would look like this:

0 0 0
0 0 161
0 0 0

and the third iteration would look like this:

0 0 0
0 0 0
0 0 0

Upvotes: 0

Views: 312

Answers (1)

LauriK
LauriK

Reputation: 1929

Well, that was fun. The main idea I guess was that I had to loop over the 1:9 matrix/array.

> library(data.table)
> r1 <- matrix(c(20,18,21,24,34,24,22,26,32), nrow=3, ncol=3)
> r1
     [,1] [,2] [,3]
[1,]   20   24   22
[2,]   18   34   26
[3,]   21   24   32
> r1.i <- as.integer(t(r1))
> rt <- matrix(c(5,5,5,5,6,5,5,0,5), nrow=3, ncol=3)
> rt
     [,1] [,2] [,3]
[1,]    5    5    5
[2,]    5    6    0
[3,]    5    5    5
> rt.i <- as.integer(t(rt))
> r.sequence <- data.table(x = 1:9)
> r3 <- r1.i
> for (i in 1:3) {
+   r3 <- r.sequence[, sum(r3[which(rt.i == x)]), by=x]
+   r3 <- r3$V1
+   print(matrix(r3, nrow=3, ncol=3, byrow=T))
+ }
     [,1] [,2] [,3]
[1,]    0    0    0
[2,]    0  161   34
[3,]    0    0    0
     [,1] [,2] [,3]
[1,]    0    0    0
[2,]    0    0  161
[3,]    0    0    0
     [,1] [,2] [,3]
[1,]    0    0    0
[2,]    0    0    0
[3,]    0    0    0

Upvotes: 1

Related Questions