How do I divide one data.table by another in R, columnwise?

Viewed 550

Consider the following:

data(cars)
library(data.table)
A <- data.table(cars)
B <- data.table(speed = 10, dist = 100)

I would like to divide the first column of A by the first element in B and the second column of A by the second element in B. So: A[,1]/B[,1] , A[,2]/B[,2], ... The output should look like:

      speed    dist
 1:     0.4   0.02
 2:     0.4   0.10
 3:     0.7   0.04
 4:     0.7   0.22
        ...

(This is a toy example. I'm hoping to turn it into a function I can run over different datasets.)

3 Answers

We can use Map

library(data.table)
A[, Map(`/`, .SD, B)]
#    speed dist
# 1:   0.4 0.02
# 2:   0.4 0.10
# 3:   0.7 0.04
# 4:   0.7 0.22
# 5:   0.8 0.16

akrun's data.table solution looks good. Here I offer an alternative, which does not require any library.

> do.call("rbind", apply(A, 1, function(x) x / B))
    speed dist
 1:   0.4 0.02
 2:   0.4 0.10
 3:   0.7 0.04
 4:   0.7 0.22
 5:   0.8 0.16

You can replicate the rows in shorter dataframe to match with longer dataframe and directly divide.

library(data.table)
A/B[rep(1, nrow(A))]

#    speed dist
# 1:   0.4 0.02
# 2:   0.4 0.10
# 3:   0.7 0.04
# 4:   0.7 0.22
# 5:   0.8 0.16
# 6:   0.9 0.10
# 7:   1.0 0.18
# 8:   1.0 0.26
# 9:   1.0 0.34
#10:   1.1 0.17
#.....
Related