[R] Applying a function to a matrix using indexes as arguments

David Winsemius dwinsemius at comcast.net
Thu Dec 17 18:54:22 CET 2015


> On Dec 17, 2015, at 8:38 AM, David L Carlson <dcarlson at tamu.edu> wrote:
> 
> Also
> 
> A %*% t(B) / C
> 

Which would be equivalent to:

> outer(A, B)/C
           [,1]      [,2]       [,3]
[1,]   10863.03 -14390.53 -287691.41
[2,] -127580.06 -13576.77   83597.56

And perhaps even more efficiently: tcrossprod(A,B)/C

The OP will need to determine whether the "other argument" he mentioned can be applied to this result in a similarly "vectorized" manner. The reason that I chose  `mapply` was that its `MoreArgs`-parameter provided an explicit mechanism for passing a further argument list to the function inside the implicit loop.

-- 
David.
> 
> Which works because when a vector is converted to a matrix, it becomes a 1-column matrix. The documentation for t() points this out but there is a typo:
> 
> "When x is a vector, it is treated as a column, i.e., the result is a 1-row matrix."
> 
> Should be a "1-column matrix"
> 
>> as.matrix(A)
>     [,1]
> [1,]  100
> [2,]  200
> 
> -------------------------------------
> David L Carlson
> Department of Anthropology
> Texas A&M University
> College Station, TX 77840-4352
> 
> -----Original Message-----
> From: R-help [mailto:r-help-bounces at r-project.org] On Behalf Of Jeff Newmiller
> Sent: Wednesday, December 16, 2015 7:01 PM
> To: Matteo Richiardi; r-help at r-project.org
> Subject: Re: [R] Applying a function to a matrix using indexes as arguments
> 
> Would
> 
> outer( A, B, `*` ) / C
> 
> do the trick for you? 
> -- 
> Sent from my phone. Please excuse my brevity.
> 
> On December 16, 2015 4:41:13 PM PST, Matteo Richiardi <matteo.richiardi at gmail.com> wrote:
>> My problem is of course more complicated, and is obviously not a
>> homework.
>> I just wanted to provide a minimal working example. You can replace the
>> matrix C with a matrix containing any number, for what matters. Btw,
>> because numbers are extracted from a Gaussian distribution, the
>> likelihood
>> that you draw a 0 is actually zero.
>> 
>> Apart from this, apologies for having posted an html version.
>> 
> snipped 
>>> 
>>> On December 16, 2015 4:18:56 PM PST, Matteo Richiardi <
>>> matteo.richiardi at gmail.com> wrote:
>>> 
>>>> I have to evolve each element of a matrix W
>>>> 
>>>> W <- matrix(0,2,3)
>>>> 
>>>> according to some function which uses the indices of the matrix
>> [i,j] as
>>>> arguments:
>>>> w.fun = function(i,j) {
>>>>  return A[i]*B[j]/(C[i,j])
>>>> }
>>>> 
>>>> where
>>>> A<-c(100,100)
>>>> B<-c(200,200,200)
>>>> C <- matrix( rnorm(6,mean=0,sd=1), 2, 3)
>>>> 
>>>> How can I do it, without recurring to a loop? Also, in my
>> application I
>>>> need to pass the function another argument.
>>>> 
>>>> Thanks a lot for your suggestions.
>>>> Matteo
>>>> 


David Winsemius
Alameda, CA, USA



More information about the R-help mailing list