From dwinsemius at comcast.net  Thu Dec  8 22:59:20 2016
From: dwinsemius at comcast.net (David Winsemius)
Date: Thu, 8 Dec 2016 13:59:20 -0800
Subject: [Rd] wish list:  generalized apply
In-Reply-To: <DM2PR0601MB8110B86F5689F2B1AF7CE0FC6840@DM2PR0601MB811.namprd06.prod.outlook.com>
References: <DM2PR0601MB8110B86F5689F2B1AF7CE0FC6840@DM2PR0601MB811.namprd06.prod.outlook.com>
Message-ID: <8A85542C-24AF-47ED-AFB9-AE4EAB3CF32C@comcast.net>


> On Dec 8, 2016, at 12:09 PM, John P. Nolan <jpnolan at american.edu> wrote:
> 
> Dear All,
> 
> I regularly want to "apply" some function to an array in a way that the arguments to the user function depend on the index on which the apply is working.  A simple example is:
> 
> A <- array( runif(160), dim=c(5,4,8) )
> x <- matrix( runif(32), nrow=4, ncol=8 ) 
> b <- runif(8)
> f1 <- function( A, x, b ) { sum( A %*% x ) + b } 
> result <- rep(0.0,8) 
> for (i in 1:8) {
>  result[i] <- f1( A[,,i], x[,i] , b[i] )
> }
> 
> This works, but is slow.  I'd like to be able to do something like:
>    generalized.apply( A, MARGIN=3, FUN=f1, list(x=x,MARGIN=2), list(b=b,MARGIN=1) ), where the lists tell generalized.apply to pass x[,i] and b[i] to FUN in addition to A[,,i].  
> 
> Does such a generalized.apply already exist somewhere?  While I can write a C function to do a particular case, it would be nice if there was a fast, general way to do this.  

I would have thought that this would achieve the same result:

result <- sapply( seq_along(b) , function(i) { f1( A[,,i], x[,i] , b[i] )} )

Or: 

result <- sapply( seq.int( dim(A)[3] ) , function(i) { f1( A[,,i], x[,i] , b[i] )} )

(I doubt it will be any faster, but if 'i' is large, parallelism might help. The inner function appears to be fairly efficient.)
-- 

David Winsemius
Alameda, CA, USA



[Rd] wish list: generalized apply
David Winsemius