[R] Element-by-element division
Steven Yen
syen04 at gmail.com
Mon Jul 27 22:04:32 CEST 2015
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
[[alternative HTML version deleted]]
More information about the R-help
mailing list