Skip to content
Prev 369551 / 398503 Next

Reversing one dimension of an array, in a generalized case

Here is an alternative approach using apply(). Note that with apply() you are reversing rows or columns not indices of rows or columns so apply(junk, 2, rev) reverses the values in each column not the column indices. We actually need to use rev() on everything but the index we are interested in reversing:

f2 <- function(a, wh) {
    dims <- seq_len(length(dim(a)))
    dims <- setdiff(dims, wh)
    apply(apply(a, dims, rev), dims, t)
}

# Your example
j1 <- junk[ , rev(1:10), ]
j2 <- f2(junk, 2)
all.equal(j1, j2)
# [1] TRUE

# Bert's example
z1 <- f(z, 2)
z2 <- f2(z, 2)
all.equal(z1, z2)
# [1] TRUE

-------------------------------------
David L Carlson
Department of Anthropology
Texas A&M University
College Station, TX 77840-4352






-----Original Message-----
From: R-help [mailto:r-help-bounces at r-project.org] On Behalf Of Bert Gunter
Sent: Thursday, June 1, 2017 12:46 PM
To: Roy Mendelssohn - NOAA Federal <roy.mendelssohn at noaa.gov>
Cc: R-help <r-help at r-project.org>
Subject: Re: [R] Reversing one dimension of an array, in a generalized case

How about this:

f <- function(a,wh){ ## a is the array; wh is the index to be reversed
   l<- lapply(dim(a),seq_len)
   l[[wh]]<- rev(l[[wh]])
   do.call(`[`,c(list(a),l))
}

## test
z <- array(1:120,dim=2:5)

##  I omit the printouts

f(z,2)

f(z,3)


Cheers,
Bert

Bert Gunter

"The trouble with having an open mind is that people keep coming along
and sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )


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