问题
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.
回答1:
(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 )
来源:https://stackoverflow.com/questions/42596449/how-to-pass-use-string-in-to-subset