0

In a for-loop, I run in i over an array which I would like to sub-index in dimension i. How can this be done? So a minimal example would be

(A <- array(1:24, dim = 2:4))
A[2,,] # i=1
A[,1,] # i=2
A[,,3] # i=3

where I index 'by foot'. I tried something along the lines of this but wasn't successful. Of course one could could create "2,," as a string and then eval & parse the code, but that's ugly. Also, inside the for loop (over i), I could use aperm() to permute the array such that the new first dimension is the former ith, so that I can simply access the first component. But that's kind of ugly too and requires to permute the array back. Any ideas how to do it more R-like/elegantly?

The actual problem is for a multi-dimensional table() object, but I think the idea will remain the same.

Update

I accepted Rick's answer. I just present it with a for loop and simplified it further:

subindex <- c(2,1,3) # in the ith dimension, we would like to subindex by subindex[i]
for(i in seq_along(dim(A))) {
    args <- list(1:2, 1:3, 1:4)
    args[i] <- subindex[i]
    print(do.call("[", c(list(A), args)))
}

2 Answers 2

2
#Build a multidimensional array
A <- array(1:24, dim = 2:4)
# Select a sub-array 
indexNumber = 2
indexSelection = 1

# Build a parameter list indexing all the elements of A
parameters <- list(A, 1:2, 1:3, 1:4)
# Modify the appropriate list element to a single value
parameters[1 + indexNumber] <- indexSelection   
# select the desired subarray
do.call("[", parameters)
Sign up to request clarification or add additional context in comments.

Comments

0
# Now for something completely different!
#Build a multidimensional array
A <- array(1:24, dim = 2:4)
# Select a sub-array 
indexNumber = 2
indexSelection = 1

reduced <- A[slice.index(A, indexNumber) == indexSelection]
dim(reduced) <- dim(A)[-indexNumber]

# Also works on the left-side
A[slice.index(A, 2)==2] <- -1:-8

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.