How to pass/use string in [ to subset

允我心安 提交于 2019-12-12 10:32:13

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!