-2

How to pass/use string in [ to subset e.g. array. I've been thinking about something like this (for 4 dims array):

inputDims <- ",,'CCC',"

outputArray[parse(text=inputDims)]

Above doesn't work - how to achieve this?

I am not interested in using logical vector (or matrix) inside [ - just string (in a form like it is in the example) if this is possible.

RSzT
  • 307
  • 3
  • 14
  • For downvoters: could you tell me how to deal with this: http://stackoverflow.com/questions/42578273/array-subset-element-from-one-dimension-by-name-dynamically because this is more complex issue and this question is attempt to solve it... – RSzT Mar 04 '17 at 14:49
  • What are you trying to achieve? [Dynamically subset a dimension](http://stackoverflow.com/questions/42562823/subset-parts-of-array-with-dynamic-dimension)? – Roman Luštrik Mar 04 '17 at 17:41
  • If you set `idx <- "CCC"`, then `outputArray[,,idx,]` returns what you want. – IRTFM Mar 05 '17 at 00:29
  • @roman-luštrik: thx for the link - I've missed that one. `abind::asub` seems to do the trick. Additionally, I was able to go through `abind::asub` to see how it is implemented (and this code is answer for that question, now also another one form @42-). – RSzT Mar 05 '17 at 23:20

1 Answers1

0

(This seems like a horrible hack. Having trouble seeing the value in proceeding along these lines but perhaps it will clarify what is needed tobuild an R function "call".)

Use scan to create a character vector of the proper length. Then append it into a list where the array is the first element. Need to convert the "empty" positions into TRUE, to get the slicing to succeed:

vec <- scan( text= inputDims, sep="," , what="")
arglist <- list(outputArray)
arglist[ 2:(length(vec)+1) ] <- as.list(vec)
arglist[ arglist==""] <- TRUE
# Using your example in the other question
> do.call("[", arglist )
   bb bbb
a1 NA  NA
a2 NA  NA
a3 NA  NA

You were earlier referred to abind::asub, and if you ant to see what gymnastics it does with its arguments (that are not sufficiently similar to your problem) then do this with the package loaded:

getAnywhere( asub.default )
IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • Nice one - thank you! It seems that using `TRUE` for "not used" dims is crucial - I didn't figure out that. – RSzT Mar 05 '17 at 23:24
  • It's also crucial to do it after conversion to a list, since logicals would otherwise get coerced to either 'character' or 'numeric' on the basis of the mode of a vector into which this assignment were attempted. – IRTFM Mar 06 '17 at 05:04