R - divide / add to all columns in the values ​​of the data frame from the vector

I have a vector x,yand a data frame dfsuch that

NCOL(x) = NCOL(y) = ncol(df).

I would like to divide each column (all rows) into a vector x(this means: all values ​​in the column are one of dfthe values ​​of the first value in the vector x, the second column (all values) is the second column (one value) of the vector x.

The same situation for adding a vector yto columns (same).

Could you help me do this in an elegant way?

+4
source share
2 answers

We can replicate 'x' and then split 'df'

df/x[col(df)]

If we need to add 'y'

(df/x[col(df)]) + y[col(df)]

data

df <- as.data.frame(matrix(1:25, 5, 5))
x <- 1:5
y <- 6:10
+3

, , , , . , . , , , , .

akrun :

df <- as.data.frame(matrix(1:25,5L,5L));
x <- 1:5;
y <- 6:10;
t(t(df)/x + y);
##      V1   V2       V3    V4   V5
## [1,]  7 10.0 11.66667 13.00 14.2
## [2,]  8 10.5 12.00000 13.25 14.4
## [3,]  9 11.0 12.33333 13.50 14.6
## [4,] 10 11.5 12.66667 13.75 14.8
## [5,] 11 12.0 13.00000 14.00 15.0

, , :

library(microbenchmark);
akrun <- function() df/x[col(df)] + y[col(df)];
bgoldst <- function() t(t(df)/x + y);
identical(as.data.frame(bgoldst()),akrun());
## [1] TRUE
identical(bgoldst(),as.matrix(akrun()));
## [1] TRUE
identical(bgoldst(),akrun());
## [1] FALSE
microbenchmark(akrun(),bgoldst(),times=1000L);
## Unit: microseconds
##       expr     min       lq      mean   median      uq      max neval
##    akrun() 812.542 867.9235 930.60749 894.6515 922.235 2395.288  1000
##  bgoldst()  50.036  58.5890  68.82336  67.1420  71.846 1417.672  1000

akrun +1 .

+1

All Articles