[R] Get subset of n dimensional matrix

Henrique Dallazuanna wwwhsd at gmail.com
Fri Oct 9 15:22:16 CEST 2009


Try this:

x <- array(1:1000, rep(10, 3))
vList <- list(i = 4:6, j = 4:6, ... = 4:6)
do.call('[', c(list(x), vList))

On Fri, Oct 9, 2009 at 7:18 AM, Mark McDowall
<markmcdowall1 at googlemail.com> wrote:
> I want to select a subset of an array, but I want to make a function so that
> it can handle any number of dimensions.
>
> This is probably best described with an example
>
>> x <- 1:100
>> dim(x) <- c(10,10)
>> x
>      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
>  [1,]    1   11   21   31   41   51   61   71   81    91
>  [2,]    2   12   22   32   42   52   62   72   82    92
>  [3,]    3   13   23   33   43   53   63   73   83    93
>  [4,]    4   14   24   34   44   54   64   74   84    94
>  [5,]    5   15   25   35   45   55   65   75   85    95
>  [6,]    6   16   26   36   46   56   66   76   86    96
>  [7,]    7   17   27   37   47   57   67   77   87    97
>  [8,]    8   18   28   38   48   58   68   78   88    98
>  [9,]    9   19   29   39   49   59   69   79   89    99
> [10,]   10   20   30   40   50   60   70   80   90   100
>>
>> vList <- vector("list", 2)
>> vList[[1]] <- c(4:6)
>> vList[[2]] <- c(4:6)
>> x[vList[[1]],vList[[2]]]
>     [,1] [,2] [,3]
> [1,]   34   44   54
> [2,]   35   45   55
> [3,]   36   46   56
>
> but if:
>
>> x <- 1:1000
>> dim(x) <- c(10,10,10)
>
> I would would have to increase the returning call:
> x[vList[[1]],vList[[2]],vList[[3]]]
>
> What I would like to be able to do is pass x the list of lists and have it
> return the required points.
>
> Anyone have any clues on how to get over this hurdle?
>
> Thank you
>
> Mark
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>



-- 
Henrique Dallazuanna
Curitiba-Paraná-Brasil
25° 25' 40" S 49° 16' 22" O




More information about the R-help mailing list