Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reshape multidimensional array

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.

like image 222
Chris Nolte Avatar asked Oct 08 '12 17:10

Chris Nolte


1 Answers

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.)

like image 140
IRTFM Avatar answered Oct 20 '22 00:10

IRTFM