Applying weights using cosine of latitude to Raster Stack values
I am currently trying to apply weights to the original precipitation values of my Raster Stack object, called "landCO2". These weights are to take into account the differences in area between the equator and poles. However, I am not sure how to approach applying these to the existing values of the Raster Stack. The idea would be to apply the weights to the original values of each of the 138 raster layers, and then eventually plot these values on a global map with wrld_simpl. Here is what was done so far:
b <- wrld_simpl landCO2 <- mask(RCP1pctCO2Median, b)
CO2new <- rasterToPoints(landCO2)
weightCO2 <- cos(CO2new[,"y"]*(pi/180))
CO2new[,3:ncol(CO2new)] = apply(CO2new[,3:ncol(CO2new)], 2, function(x) x * weightCO2)
avgCO2 <- colSums(CO2new[,3:ncol(CO2new)])/sum(weightCO2)
However, this approach obtains an average across all grid cells per layer, effectively creating 138 averages, which is fine. That said, I would like to similarly apply the weights to the values of landCO2 instead, so that the values across the 8192 grid cells for each of the 138 raster layers are appropriately transformed using the approach above. Evidently, this would be done prior to rasterToPoints being applied.
To do what I would like, I tried the following: landCO2 <- mask(RCP1pctCO2Median,b)
weightCO2 <- cos(landCO2[,"y"]*(pi/180)) #Notice that I skipped the "rasterToPoints" stage and replaced CO2new with landCO2 to directly work with landCO2 for this
However, this results in the following error: "Error in landCO2[, "y"] : object of type 'S4' is not subsettable"
Why would the above error emerge? Is this also the correct approach to apply the weights to landCO2?