df[,-1] <- df[,-1]/div[col(df)]
df
# type V1 V2 V3
#1 A 0.1 0.01 0.001
#2 B 0.1 0.01 0.001
#3 C 0.1 0.01 0.001
str(df)
#'data.frame': 3 obs. of 4 variables:
# $ type: Factor w/ 3 levels "A","B","C": 1 2 3
# $ V1 : num 0.1 0.1 0.1
# $ V2 : num 0.01 0.01 0.01
# $ V3 : num 0.001 0.001 0.001
Benchmarks
set.seed(454)
dat <- as.data.frame(matrix(sample(200, 1e3*1e2, replace=TRUE), ncol=1e2))
set.seed(29)
div <- sample(40, 1e2, replace=TRUE)
f1 <- function() {sweep(dat, MARGIN = 2, div, FUN = "/")}
f2 <- function() {t(t(dat) / div)}
f3 <- function() { mapply("/", dat, div)}
f4 <- function() {dat/div[col(dat)]}
f5 <- function() {for(r in 1:nrow(dat)){
dat[r,]/div}}
library(microbenchmark)
microbenchmark(f1(), f2(), f3(), f4(), f5(), unit="relative")
#Unit: relative
# expr min lq median uq max neval
# f1() 6.765024 6.724991 6.434463 5.124457 10.91735 100
# f2() 1.000000 1.000000 1.000000 1.000000 1.00000 100
# f3() 18.028441 18.551529 16.742279 14.239107 13.72168 100
# f4() 6.315330 6.577099 6.333656 5.052068 10.13038 100
# f5() 4211.839669 3908.555985 3945.130154 2962.534518 1655.12268 100