I have an array representing hourly temperature data, and want to compute daily maxima (or minima, or means). I can do this using a for loop, but I am sure there must be many better ways to do this in R.
require(ncdf4)
nc <- nc_open('file.nc')
t2 <- ncvar_get(nc,var='T2') # [ncols, nrows, nsteps]
Now t2 is an array with 744 hourly time steps for a 31-day month. What I want is:
t2.max[ncols, nrows, 31]
or, more generally, I would like to reshape t2 to:
t2.reshape[ncols, nrows, ndays, 24]
and from there I can use apply to compute daily means or maxima or whatever.
I want the result to be an array, not a data frame.
Suggestions? I tried using melt/cast from the reshape package, but could not understand how to specify the desired formula.
If t2 is an array with 744 hourly time steps for a 31-day month" then it has 744 rows and other dimensions? (You did not tell us whether ncol was 744 or nrow was 744. We will assume it was nrow)
array( tc, , dim =c( 31, 24, nrows, ncols) )
If, on the other hand, it was [nrow,ncols,744] you can use aperm to recast it with the rows being as above:
array( aperm(tc, c(3,1,2)) , dim =c( 31, 24, nrows, ncols) )
There is a package that has a 'rowMax' and and a 'rowMin' function which would give you a vectorized approach that you would not need to invent. (It was in the Biobase package from the Bioconductor repository.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With