How to select part of a tensor (multidimensional array) with a vector of dimension names?

Viewed 37

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!

1 Answers

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
Related