[R] efficient way to fill up matrix (and evaluate function)

Joshua Wiley jwiley.psych at gmail.com
Mon Nov 28 06:10:54 CET 2011


Here is an example, of course, this is predicated on how myfunc()
behaves---if it could not handle adding a constant to a vector, things
would choke:

## Current method
myfunc <- function(x1, x2) {
  x1 + x2
}

x <- 1:10
n <- length(x)

A <- matrix(0, nrow = n, ncol = n)

for (i in 1:n){
  for (j in 1:n){
    A[i,j] <- myfunc(x[i], x[j])
  }
}

A

## partially vectorized
A2 <- matrix(0, nrow = n, ncol = n)

for (i in 1:n){
  A2[i, ] <- myfunc(x[i], x)
}
A2

## even more so
A3 <- myfunc(outer(rep(1, length(x)), x), x)

all.equal(A, A2, A3)

Cheers,

Josh

On Sun, Nov 27, 2011 at 8:54 PM, Sachinthaka Abeywardana
<sachin.abeywardana at gmail.com> wrote:
> Hi Jim,
>
> What exactly do you mean by vectorized. I think outer looks like what I was
> looking for. BUT there was a (weighted) distance matrix calculation that I
> was trying to vectorize, which wasnt related to this post. Could you proved
> a bit more details as to what you were referring to, and maybe an example
> as how to vectorize in R?
>
> Thanks,
> Sachin
>
> On Mon, Nov 28, 2011 at 3:25 PM, jim holtman <jholtman at gmail.com> wrote:
>
>> Take a look at 'outer'  and vectorized your function.  Also look at
>> 'expand.grid'.
>>
>>
>> On Sunday, November 27, 2011, Sachinthaka Abeywardana <
>> sachin.abeywardana at gmail.com> wrote:
>> > Hi All,
>> >
>> > I want to do something along the lines of:
>> > for (i in 1:n){
>> >    for (j in 1:n){
>> >        A[i,j]<-myfunc(x[i], x[j])
>> >    }
>> > }
>> >
>> > The question is what would be the most efficient way of doing this. Would
>> > using functions such as sapply be more efficient that using a for loop?
>> >
>> > Note that n can be a few thousand. Thus atleast a 1000x1000 matrix.
>> >
>> > Thanks,
>> > Sachin
>> >
>> >        [[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.
>> >
>>
>> --
>> Jim Holtman
>> Data Munger Guru
>>
>> What is the problem that you are trying to solve?
>> Tell me what you want to do, not how you want to do it.
>>
>
>        [[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.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
Programmer Analyst II, ATS Statistical Consulting Group
University of California, Los Angeles
https://joshuawiley.com/



More information about the R-help mailing list