[R] Matrix multiplication using apply() or lappy() ?

Gabor Grothendieck ggrothendieck at gmail.com
Wed Sep 6 18:08:35 CEST 2006


And here is one more:

t(apply(a, 1, function(x) x/a[1,]))

On 9/6/06, Gabor Grothendieck <ggrothendieck at gmail.com> wrote:
> Here are a few possibilities:
>
> a <- matrix(1:24, 4) # test data
>
> a / rep(a[1,], each = 4)
>
> a / outer(rep(1, nrow(a)), a[1,])
>
> a %*% diag(1/a[1,])
>
> sweep(a, 2, a[1,], "/")
>
>
> On 9/6/06, toby_marks at americancentury.com
> <toby_marks at americancentury.com> wrote:
> > I am trying to divide the columns of a matrix by the first row in the
> > matrix.
> >
> > I have tried to get this using apply and I seem to be missing a concept
> > regarding the apply w/o calling a function but rather command args %*% /
> > etc.  Would using apply be more efficient than this approach?
> >
> > I have observed examples in the archives using this type of approach. Does
> > anybody have a snippet of a call to apply() that would accomplish this as
> > well?
> >
> > Thanks!
> >
> >
> > seed=50
> > $a = array(rnorm(20),dim=c(4,5))
> > $b = matrix(a[1,],dim(a)[1],dim(a)[2],byrow=T)
> > $a
> >           [,1]       [,2]       [,3]        [,4]       [,5]
> > [1,] -1.3682810 -0.4314462 1.57572752  0.67928882 -0.3672346
> > [2,]  0.4328180  0.6556479 0.64289931  0.08983289  0.1852306
> > [3,] -0.8113932  0.3219253 0.08976065 -2.99309008  0.5818237
> > [4,]  1.4441013 -0.7838389 0.27655075  0.28488295  1.3997368
> >
> > $a/b
> >           [,1]       [,2]       [,3]       [,4]      [,5]
> > [1,]  1.0000000  1.0000000 1.00000000  1.0000000  1.000000
> > [2,] -0.3163225 -1.5196515 0.40800157  0.1322455 -0.504393
> > [3,]  0.5930018 -0.7461539 0.05696457 -4.4062113 -1.584338
> > [4,] -1.0554128  1.8167710 0.17550671  0.4193841 -3.811560
> >
> >
> >
> > ------------------------------------------------------------
> > CONFIDENTIALITY NOTICE: This electronic mail transmission (i...{{dropped}}
> >
> > ______________________________________________
> > 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