[Rd] x[1,], x[1,,], x[1,,,], ...

Liaw, Andy andy_liaw at merck.com
Wed Nov 23 14:02:29 CET 2005


I suppose one can make use of slice.index():

> array(x[slice.index(x, 1) == 1], dim(x)[-1])
     [,1] [,2]
[1,]    1   13
[2,]    5   17
[3,]    9   21

Andy


> From: Henrik Bengtsson
> 
> Hi,
> 
> is there a function in R already doing what I try to do below:
> 
> # Let 'x' be an array with *any* number of dimensions (>=1).
> x <- array(1:24, dim=c(2,2,3,2))
> ...
> x <- array(1:24, dim=c(4,3,2))
> 
> i <- 2:3
> 
> ndim <- length(dim(x))
> if (ndim == 1)
>    y <- x[i]
> else if (ndim == 2)
>    y <- x[i,]
> else if (ndim == 3)
>    y <- x[i,,]
> else ...
> 
> and so on.  My current solution is
> 
> ndim <- length(dim(x))
> args <- rep(",", ndim)
> args[1] <- "i"
> args <- paste(args, collapse="")
> code <- paste("x[", args, "]", sep="")
> expr <- parse(text=code)
> y <- eval(expr)
> 
> ndim <- length(dim(x))
> args <- rep(",", ndim)
> args[1] <- "i"
> args <- paste(args, collapse="")
> code <- paste("x[", args, "]", sep="")
> expr <- parse(text=code)
> y <- eval(expr)
> 
> Is there another way I can do this in R that I have overlooked?
> 
> /Henrik
> 
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
> 
>



More information about the R-devel mailing list