coco
coco

Reputation: 31

Dividing first element of a column vector of dimension 3x1 with column vector of dimension 5x1 and so on in R

I have the following example with two column vectors:

a = [1,2,3]
b = [4,5,6,7,8]

and I want the following:

1/4,1/5,1/6,1/7,1/8,2/4,2/5,2/6,2/7,2/8,3/4,3/5,3/6,3/7,3/8

I will appreciate your help. Note that / is the division operator. Thanks.

Upvotes: 0

Views: 70

Answers (1)

akrun
akrun

Reputation: 887158

You could use outer

c(outer(a,b, FUN="/"))
#[1] 0.2500000 0.5000000 0.7500000 0.2000000 0.4000000 0.6000000 0.1666667
#[8] 0.3333333 0.5000000 0.1428571 0.2857143 0.4285714 0.1250000 0.2500000
#[15] 0.3750000

If you want it as fractions

library(MASS)
fractions(c(outer(a,b, FUN="/")))
#[1] 1/4 1/2 3/4 1/5 2/5 3/5 1/6 1/3 1/2 1/7 2/7 3/7 1/8 1/4 3/8

Or if you want to represent it like this

 c(t(outer(a[,1], b[,1], FUN= paste, sep="/")))
 #[1] "1/4" "1/5" "1/6" "1/7" "1/8" "2/4" "2/5" "2/6" "2/7" "2/8" "3/4" "3/5"
 #[13] "3/6" "3/7" "3/8"

data

a <- matrix(1:3)
b <- matrix(4:8)

Upvotes: 1

Related Questions