I downloaded a monthly precipitation data in netcdf format from NOAA (CPC Unified guage). The data were stored in mm/day and I need to multiply each layer with counts of their respective month to get the total precipitation for the month. For instance, a layer for September 1969 will be multiplied by 30 while the layer for February will be multiplied by 28. Also, there's a problem of leap years when February layers will have to be multiplied by 29.
I tried some codes (see below) but are not working.
prec <- brick(precip.V1.0.mon.mean.nc)
conv <- function(x, ...) {
ifelse(x == c(01, 03, 05, 07, 08, 09, 10, 12),
31 * x,
x,
ifelse(x == c(04, 06, 11),
30 * x,
x,
ifelse(x == 02,
28 * x,
x)))
} # function for the conversion
## pulling out date indices for each month
indices <- as.numeric(format(as.Date(names(prec), format = "X%Y.%m.%d"), format = "%m"))
## applying the function using stackApply
new_prec <- stackApply(prec, indices, fun = conv)
Error in ifelse(x == c(1, 2, 3, 5, 7, 8, 9, 10, 12), 31 * x, x, ifelse(x == : unused argument (ifelse(x == c(4, 6, 11), 30 * x, x, ifelse(x == 2, 28 * x, x)))
And when I tried to pass the function using a simplified version (e.g.) ifelse(x == 12, 30*x, x) I got the following error
Error: Error in (function (..., deparse.level = 1) : number of rows of matrices must match (see arg 2)
I was wondering if anyone has tips for the conversion.
Here's a link to a subset of the the data: https://fil.email/VahwQq8p