[R] filling an array, vectorized
Gabor Grothendieck
ggrothendieck at gmail.com
Thu Nov 16 12:27:56 CET 2006
Here is minor simplification:
do.index2 <- function(a,f){
jj <- function(i) seq(dim(a)[i])
index <- as.matrix(expand.grid(lapply(jj(TRUE), jj)))
a[index] <- apply(index, 1, f)
a
}
# test
a <- array(0,c(2,3,4))
identical(do.index(a, f), do.index2(a, f))
b <- array(0,c(2,2,2,2))
identical(do.index(b, f), do.index2(b, f))
On 11/16/06, Robin Hankin <r.hankin at noc.soton.ac.uk> wrote:
> Tamas
>
> first of all, Thank You for a really well-posed, interesting problem.
> Answer follows.
>
>
>
> do.index <- function(a,f){
> jj <- function(i){seq_len(dim(a)[i])}
> index <- as.matrix(expand.grid(sapply(1:length(dim
> (a)),jj,simplify=FALSE)))
> a[index] <- apply(index,1,f)
> return(a)
> }
>
>
>
> f <- function(l){
> sum(unlist(l))
> }
>
> a <- array(0,c(2,3,4))
> b <- array(0,c(2,2,2,2))
>
> do.index(a,f)
> do.index(b,f)
>
>
>
> best wishes
>
> Robin
>
>
>
>
>
> On 15 Nov 2006, at 19:16, Tamas K Papp wrote:
>
> > Hi,
> >
> > I am sure this has come up before, but my searches of the archive
> > didn't give any results (maybe I didn't use the right keywords, but if
> > I use too many, the search times out).
> >
> > I have a vector of dimensions n, length is not fixed, eg
> >
> > n <- c(4,5,7)
> >
> > or
> >
> > n <- c(19,4,5,7)
> >
> > and a function f that takes a vector of indices, same length of n, and
> > gives a scalar.
> >
> > I would like to fill the array
> >
> > a <- array(dim=n)
> >
> > so that (... is just notation, not R's ...)
> >
> > a[i,j,k,...] <- f(list(i,j,k,...))
> >
> > I would use loops, but since n can have different lengths, I don't
> > know how many loops I would need beforehand. Is there a way to do
> > this?
> >
> > Thanks,
> >
> > Tamas
> >
> > ______________________________________________
> > R-help at stat.math.ethz.ch 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.
>
> --
> Robin Hankin
> Uncertainty Analyst
> National Oceanography Centre, Southampton
> European Way, Southampton SO14 3ZH, UK
> tel 023-8059-7743
>
> ______________________________________________
> R-help at stat.math.ethz.ch 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