Yes, the matrix statement above is what arranges the months by year, so the differencing will work a year ahead instead of a month ahead. My code is also in R, and so probably will not be easier to understand. In principle, I could unroll all the special operations like filtering into for loops, etc., to make the logic more clear, but I don't really feel like it. It shouldn't be too hard for you to replicate yourself if you know any programming languages; it's just averaging and subtraction.

(For reference, 'matrix' in R makes a matrix where the last 2 arguments are the dimensions and the first argument is a vector of values. 'rep' makes a vector by repeating some number. 'NA' is the "number" being repeated; in this case, it's "not applicable", i.e. missing data. The actual numerical values are assigned later after the matrix is created. It's common to initialize data structures with 'NA' because if you forget to assign them later, your results will always be NA and you'll notice there's a problem.)