# Addition and subtraction of rasterbrick objects in R

I have two rasterbrick objects showing precipitation. Both have longitude and latitude dimensions of 144 x 72. The first (brick1) has 478 monthly time layers (39 years, 10 months) running from Jan 1979 to Oct 2018. The second (brick2) has 12 monthly time layers (Jan through Dec) representing the monthly mean values for 1981-2010. I want to calculate an anomaly by subtracting the geographically appropriate monthly mean from each data point. I did this:

``````anom <- brick1-brick2
``````

R did not complain - but I am not sure if I got what I wanted.

My hope is that R will subtract the January through December means first against 1979, then it will recycle those means identically through each year until 2018, and in 2018 it will apply only the first 10 means (Jan through October). I have not been able to find any documentation that indicates whether this is the way it is actually done. I have seen some statements to the effect that some operations recycle smaller objects against the larger ones, but nothing specifically about rasterbricks. Does anybody know?

It will work if you have a multiple, but it won't work if there are layers remaining:

``````library(raster)
m1 = array(dim=c(2,2,2),
data = c(0,1,2,3,
4,5,6,7))
m2 = array(dim=c(2,2,6),
data = c(1,1,0,0,
1,2,1,2,
4,5,4,5,
5,6,5,6,
-1,0,-1,0,
1,0,1,0))
r1 = brick(m1)
r2=brick(m2)

r3 = r2-r1

plot(r1)
plot(r2)
plot(r3)
``````

`plot(r3)` shows that layers are subtracted sequentially and iteratively. But if you change `m2` to...

``````m2 = array(dim=c(2,2,7),
data = c(1,1,0,0,
1,2,1,2,
4,5,4,5,
5,6,5,6,
-1,0,-1,0,
1,0,1,0,
0,0,0,0))
``````

... it won't work anymore because the longer object is not a multiple of the shorter object. If I were you I'd do the big subtraction using only complete years, and then subset the 12-month mean rasterbrick to only include data through October and subtract 2018's Jan-Oct data from that.

• JepsonNomad, thanks for the example. It illustrated the issue well. I would have responded earlier but I am still learning how to subset and recombine the bricks. Here's what I wound up with: >`sub1 <- subset(brick1,1:468) - brick2` >`sub2 <- subset(brick1,469:478) - subset(brick2,1:10)` >`anom1 <- addLayer(sub1,sub2)` I subtracted my old calculation from the new one and sure enough, only the last year was different - so it seems to have worked. (Sorry, I can't figure out how to format these comments).
– jbtg
Feb 28 '19 at 3:32
• @jbtg Glad you got it working. If that clears everything up you can go ahead and mark this resolved. Feb 28 '19 at 3:56