[R] building a subscript programatically

Henrik Bengtsson hb at biostat.ucsf.edu
Wed Nov 2 04:10:47 CET 2011


2011/11/1 Ernest Adrogué <nfdisco at gmail.com>:
> Hi,
>
> On ocasion, you need to subscript an array that has an arbitrary
> (ie. not known in advance) number of dimensions. How do you deal with
> these situations?
> It appears that it is not possible use a list as an index, for
> instance this fails:
>
>> x <- array(NA, c(2,2,2))
>> x[list(TRUE,TRUE,2)]
> Error in x[list(TRUE, TRUE, 2)] : invalid subscript type 'list'
>
> The only way I know is using do.call() but it's rather ugly. There
> must be a better way!!
>
>> do.call('[', c(list(x), TRUE, TRUE, 2))
>     [,1] [,2]
> [1,]   NA   NA
> [2,]   NA   NA
>
> Any idea?

> library("R.utils")
> x <- array(1:8, dim=c(2,2,2))
> x
, , 1
     [,1] [,2]
[1,]    1    3
[2,]    2    4
, , 2
     [,1] [,2]
[1,]    5    7
[2,]    6    8

> extract(x, "3"=2)
, , 1
     [,1] [,2]
[1,]    5    7
[2,]    6    8

For more details/examples, see help("extract.array", package="R.utils").

It doesn't to assignments, but could be achieved by:

idxs <- array(seq(along=x), dim=dim(x))
idxs <- extract(idxs, "3"=2)
x[idxs] <- ...

base::arrayInd() may also be useful.

/Henrik

>
> Regards,
> Ernest
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list