[R] Element-by-element multiplication

Steven Yen syen04 at gmail.com
Mon May 23 00:22:59 CEST 2016


Dear R users:

 > # p is a vector if length 10
 > # a is a vector if length 3
 > # I like to create a matrix with
 > # the first  column being p multiplied by a[1]
 > # the second column being p multiplied by a[2]
 > # the third  column being p multiplied by a[3]
 > # The following would do that:
 >
 > a<-c(10,100,1000); a
[1]   10  100 1000
 > p<-matrix(1:10,nrow=10); p
       [,1]
  [1,]    1
  [2,]    2
  [3,]    3
  [4,]    4
  [5,]    5
  [6,]    6
  [7,]    7
  [8,]    8
  [9,]    9
[10,]   10
 > cbind(a[1]*p,a[2]*p,a[3]*p)
       [,1] [,2]  [,3]
  [1,]   10  100  1000
  [2,]   20  200  2000
  [3,]   30  300  3000
  [4,]   40  400  4000
  [5,]   50  500  5000
  [6,]   60  600  6000
  [7,]   70  700  7000
  [8,]   80  800  8000
  [9,]   90  900  9000
[10,]  100 1000 10000
 >
 > # Gauss does it easily with an element-by-element
 > # multiplicationa.*p
 > # How can I do this in R?
 >


	[[alternative HTML version deleted]]



More information about the R-help mailing list