[R] Multiplying elements of vectors

Phil Spector spector at stat.berkeley.edu
Sun Feb 6 05:54:33 CET 2011


If the seq(5,205) was a typo, and should have been
seq(5,20,5), then what you're looking for is the outer
product of x and y:

> x = seq(5,20,5)
> y = seq(5,20,5)
> x %o% y
      [,1] [,2] [,3] [,4]
[1,]   25   50   75  100
[2,]   50  100  150  200
[3,]   75  150  225  300
[4,]  100  200  300  400
> outer(x,y)
      [,1] [,2] [,3] [,4]
[1,]   25   50   75  100
[2,]   50  100  150  200
[3,]   75  150  225  300
[4,]  100  200  300  400

The outer() function will accepts a FUN= argument 
which defaults to '*'.

 					- Phil Spector
 					 Statistical Computing Facility
 					 Department of Statistics
 					 UC Berkeley
 					 spector at stat.berkeley.edu


On Sat, 5 Feb 2011, Mariana Martinez-Morales wrote:

> Hi guys:
>
> Sorry if this question is very basic. I’m learning basic matrix and
> vectors multiplication to develop a population matrix model for
> plants. I’m trying to multiply the elements of two vectors (each of
> the “x” values by each of the “y” values) to obtain a square matrix of
> xy values.
>
> f.e.
> x<-seq(5,205)
> y<-seq(5,20,5)
> stages<-c(“Sdl”, “Juv”, “Ad1”, “Ad2”)
>
> If I just multiply xy as a matrix
> xy<-matrix(x,y,nrow=4,ncol=4,dimnames=list(stages,stages))
>
> I obtain this
>
> xy
>        Sdl Juv A1 A2
> Sdl   5  10 15 20
> Juv   5  10 15 20
> A1    5  10 15 20
> A2    5  10 15 20
>
> but what I want to obtain is this matrix
>
>        Sdl    Juv     A1    A2
> Sdl   25    50      75     100
> Juv   50    100    150   200
> A1    75    50      225   300
> A2    100  200    300   400
>
> ______________________________________________
> 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.
>


More information about the R-help mailing list