3

During a project in R I met this problem and I am really confused:

For example, I have a tensor T (dimension 3x2x2) and a vector A

T <- array(c(1,2,3,4,5,6,7,8,9,10,11,12), dim=c(3,2,2), dimnames=list(c("X","Y","Z"),c("1","2"),c("a","b")))
A <- c(NA, "2","b")

I'm wondering how can I get T[ ,"2","b"] with the use of vector A? I tried T[A] as long as many other things but it doesn't seem to work. Note that A is a variable and it could very well become A <- c(NA, NA,"a") and we would like to have T[ , ,"a"] in this case.

Thank you very much for your help!

Xuwen Liu
  • 33
  • 5
  • 1
    I am not sure what you're seeking is possible by standard means in R. The first and simplest method is to create a list with arguments for the `[` function and use `do.call([, args)` (note missing hyphens for the bracket, due to markdown). But it this simply does not work: `v – Oliver Jun 09 '21 at 12:31
  • Have also a look at: [Subset an array using a vector of indices](https://stackoverflow.com/q/53013962/10488504) – GKi Jun 09 '21 at 12:39

1 Answers1

2

Try this (a little convoluted):

A2<-as.list(A)
A2[is.na(A)]<-TRUE
do.call(`[`,c(list(T),A2))
# X  Y  Z 
#10 11 12
nicola
  • 23,063
  • 3
  • 31
  • 52