[R] On matrix calculation

arun smartpink111 at yahoo.com
Wed Apr 17 15:00:33 CEST 2013


Hi,
Try:
sweep(Mat,1,Vec,"/")
 #         [,1] [,2]     [,3]
#[1,] 0.2000000    1 1.800000
#[2,] 0.3333333    1 1.666667
#[3,] 0.4285714    1 1.571429
#[4,] 0.5000000    1 1.500000


do.call(rbind,lapply(seq_len(nrow(Mat)),function(i) Mat[i,]/Vec[i]))
#          [,1] [,2]     [,3]
#[1,] 0.2000000    1 1.800000
#[2,] 0.3333333    1 1.666667
#[3,] 0.4285714    1 1.571429
#[4,] 0.5000000    1 1.500000
A.K.



----- Original Message -----
From: Christofer Bogaso <bogaso.christofer at gmail.com>
To: r-help <r-help at r-project.org>
Cc: 
Sent: Wednesday, April 17, 2013 8:39 AM
Subject: [R] On matrix calculation

Hello again,

Let say I have a matrix:

Mat <- matrix(1:12, 4, 3)

And a vector:

Vec <- 5:8

Now I want to do following:

Each element of row-i in 'Mat' will be divided by i-th element of Vec

Is there any direct way to doing that?

Thanks for your help

______________________________________________
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