Not sure it is "obvious", but this function implements what you describe:

revdim <- function( a, d ) {
   dims <- attr( a, "dim" )
   idxs <- lapply( seq_along( dims )
                 , function( dd ) {
                     if ( d == dd ) seq.int( dims[ dd ], 1, -1 )
                     else seq.int( dims[ dd ] )
                   }
                 )
   do.call( `[`, c( list( a ), idxs ) )
}

revdim( junk1, 2 )

On Thu, 1 Jun 2017, Roy Mendelssohn - NOAA Federal wrote:

Hi All:

I have been looking for an elegant way to do the following, but haven't found it, I have never had a good understanding of any of the "apply" functions.

A simplified idea is I have an array, say:

junk(5, 10, 3)

where (5, 10, 3) give the dimension sizes, and I want to reverse the second dimension, so I could do:

junk1 <- junk[, rev(seq_len(10), ]

but what I am after is a general function that will do that where the array could be two, three or four dimensions, and I pass to the function which dimension I want to reverse, that is the function can not assume the number of dimensions of the array nor which dimension to reverse.

For example,  if i try:

junk1 <- apply(junk, 2, rev)

junk1 comes out as two-dimensional,  not three-dimensional.

It is probably something obvious but I am not getting it.

Thanks for any help.

-Roy



---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnew...@dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                      Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k

______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to