[R] Element-by-element division

Sarah Goslee sarah.goslee at gmail.com
Mon Jul 27 22:17:07 CEST 2015


Hi,

See ?sweep

For instance, to get your matrix two:

> sweep(a, 2, b, "/")
     [,1] [,2]
[1,]    2   24
[2,]    4   28
[3,]    6   32
[4,]    8   36
[5,]   10   40


Sarah

On Mon, Jul 27, 2015 at 4:04 PM, Steven Yen <syen04 at gmail.com> wrote:
> I need help with element-by-element division. Below, matrices a and c are
> both 5 x 2 and element-by-element division works as (I) expected. What if
> matrix is 1 by 2: to divide first column of a by b[1] and second column of
> a by b[2]. I had to go around (two ways) to make it work. In Gauss, these
> can be dine by a./b and a./c. Any such simple way in R? Thank!
>
>> a<-matrix(1:10,nrow=5); a
>      [,1] [,2]
> [1,]    1    6
> [2,]    2    7
> [3,]    3    8
> [4,]    4    9
> [5,]    5   10
>> b<-matrix(c(0.5,0.25),nrow=1); b
>      [,1] [,2]
> [1,]  0.5 0.25
>> c<-matrix(rep(c(0.5,0.25),5),nrow=5,byrow=T); c
>      [,1] [,2]
> [1,]  0.5 0.25
> [2,]  0.5 0.25
> [3,]  0.5 0.25
> [4,]  0.5 0.25
> [5,]  0.5 0.25
>
>> one<-a/c; one     [,1] [,2]
> [1,]    2   24
> [2,]    4   28
> [3,]    6   32
> [4,]    8   36
> [5,]   10   40
>
>
>> two<-a/b
> Error in a/b : non-conformable arrays
>> two<-cbind(a[,1]/b[1],a[,2]/b[2]); two
>      [,1] [,2]
> [1,]    2   24
> [2,]    4   28
> [3,]    6   32
> [4,]    8   36
> [5,]   10   40
>
>> b2<-matrix(rep(b,5),nrow=5,byrow=T); b2     [,1] [,2]
> [1,]  0.5 0.25
> [2,]  0.5 0.25
> [3,]  0.5 0.25
> [4,]  0.5 0.25
> [5,]  0.5 0.25> a/b2     [,1] [,2]
> [1,]    2   24
> [2,]    4   28
> [3,]    6   32
> [4,]    8   36
> [5,]   10   40

-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list