# How to get the upstream average of a raster data layer that falls into a river network?

I have a raster layer of a network of rivers and a raster layer of data I want to extract.

For each pixel of the rivers, I need to know the upstream average of the data layer that falls into the river. Kind of like a mix between Flow Accumulation and Zonal Statistics.

Understanding "average" to be the arithmetic mean, recall this is a ratio of two sums: the numerator is the sum of values from the other "data layer" and the denominator is a sum of ones (one per cell). Because Flow accumulation performs the summation, all you have to do is compute a Flow accumulation of the layer, compute another Flow accumulation of a 0-1 indicator of the layer's presence, and then divide the first by the second.

This is the solution I gave at https://gis.stackexchange.com/a/8408/664 to the same--but more specific--problem of computing proportion of landuse within upstream areas. That proportion can also be expressed as an average (of the landuse indicator values).