1

Let's assume we've a 3-dimensional array like

a <- array(1:24, dim = c(4, 3, 2))

Accessing or indexing an array is usually done via

# fixing the third (=last) dimension and output the corresponding values of the first and second dimension
a[, , 1] 

> a
, , 1

     [,1] [,2] [,3]
[1,]    1    5    9
[2,]    2    6   10
[3,]    3    7   11
[4,]    4    8   12

In this example, I know the number of dimensions is three. So, I can manually type two commas followed by a number for the last dimension (here 1). But now I want to create an expression for dynamically indexing an array by fixing the last dimension a priori not knowing the number of dimensions. This construct should later be used within a loop e.g. lapply().

dims <- paste0(paste0(rep("", length(dim(a)) - 1L), collapse = ","), ",idx")

> dims
[1] ",,idx"

Am I able to convert this dynamically created string ",,idx" into whatever - I know that indexing by itself isn't strongly an expression, that can be used for indexing?

a[dims] <- ... # won't work!

Thanks in advance!

stschn
  • 121
  • 7
  • what exactly do you want this for? What do you want to accomplish? – Onyambu May 27 '21 at 16:58
  • 1
    https://stackoverflow.com/questions/67536201/is-there-a-way-to-select-all-elements-of-a-dimension-when-matrix-indexing-a-mult?answertab=votes#tab-top – user20650 May 27 '21 at 17:01
  • @Onyambu I want to write a function which is able to insert an array into another array on a certain position regarding the last dimension. It's a kind of abind() but with choosing the position where the inserted array should appear. – stschn May 27 '21 at 17:20
  • 2
    try `do.call('[', c(list(a), rep(list(TRUE), length(dim(a))-1), 1))` – Onyambu May 27 '21 at 17:22
  • @all thanks for your quick response! – stschn May 27 '21 at 17:24

1 Answers1

0

Here is a way, but I'm not sure it's the way you want:

write.table(paste0("a[",dims,"]"),"code.R",row.names = FALSE,col.names = FALSE,quote=FALSE)
source("code.R")$value

This will create a separate R script which contains just the a[,,idx] and then run that script to return the value.