[R] Reversing one dimension of an array, in a generalized case

David Winsemius dwinsemius at comcast.net
Fri Jun 2 03:51:06 CEST 2017

```> On Jun 1, 2017, at 9:51 AM, Roy Mendelssohn - NOAA Federal <roy.mendelssohn at noaa.gov> 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.

It was clear whether you wanted every slice along a particular dimension reversed or just one particular slice in a particular dimension. I thought probably the former:

Try:

(arr <- array(1:(2*3*4), dim=c(2,3,4) ) )

array( apply(arr, 3, rev), dim (arr) )

--
David.
>
> Thanks for any help.
>
> -Roy
>
>
> **********************
> "The contents of this message do not reflect any position of the U.S. Government or NOAA."
> **********************
> Roy Mendelssohn
> Supervisory Operations Research Analyst
> NOAA/NMFS
> Environmental Research Division
> Southwest Fisheries Science Center
> 110 McAllister Way
> Santa Cruz, CA 95060
> Phone: (831)-420-3666
> Fax: (831) 420-3980
> e-mail: Roy.Mendelssohn at noaa.gov www: http://www.pfeg.noaa.gov/
>
> "Old age and treachery will overcome youth and skill."
> "From those who have been given much, much will be expected"
> "the arc of the moral universe is long, but it bends toward justice" -MLK Jr.
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help