swiss_buda
swiss_buda

Reputation: 79

In R, apply multiply two data frames element-wise and by a vector

With a data frame

d <- data.frame("A" = c(1.1, 2.1, 3.1, 4.1), "B" = c(5.5, 6.6, 7.7, 8.8))
  A   B
1 1.1 5.5
2 2.1 6.6
3 3.1 7.7
4 4.1 8.8

and two vectors

e <- c(10, 20, 30, 40)
[1] 10 20 30 40

ti <- seq(0, 5)
[1] 0 1 2 3 4 5

i obtained the output

a1 <- lapply(d, function(x) mapply(function(x, y) x * y * ti, x, e))
$A
     [,1] [,2] [,3] [,4]
[1,]    0    0    0    0
[2,]   11   42   93  164
[3,]   22   84  186  328
[4,]   33  126  279  492
[5,]   44  168  372  656
[6,]   55  210  465  820

$B
     [,1] [,2] [,3] [,4]
[1,]    0    0    0    0
[2,]   55  132  231  352
[3,]  110  264  462  704
[4,]  165  396  693 1056
[5,]  220  528  924 1408
[6,]  275  660 1155 1760

If i replace vector e with a data frame

f <- data.frame("A" = c(10, 20, 30, 40), "B" = c(50, 60, 70, 80))
   A  B
1 10 50
2 20 60
3 30 70
4 40 80

how can i obtain the output

$A
     [,1] [,2] [,3] [,4]
[1,]    0    0    0    0
[2,]   11   42   93  164
[3,]   22   84  186  328
[4,]   33  126  279  492
[5,]   44  168  372  656
[6,]   55  210  465  820
$B
     [,1] [,2] [,3] [,4]
[1,]    0    0    0    0
[2,]  275  396  539  704
[3,]  550  792 1078 1408
[4,]  825 1188 1617 2112
[5,] 1100 1584 2156 2816
[6,] 1375 1980 2695 3520

so that d and f are operated on element-wise?

I know that d and f will always be of identical dimensions.

Update:

Also, is there a solution that would work with a more complicated function like d * exp(ti * f) instead of d * ti * f?

Upvotes: 3

Views: 1428

Answers (2)

lmo
lmo

Reputation: 38510

In base R with Map and outer, you can do

Map(function(x, y) t(outer(x, ti) * y), d, f)
$A
     [,1] [,2] [,3] [,4]
[1,]    0    0    0    0
[2,]   11   42   93  164
[3,]   22   84  186  328
[4,]   33  126  279  492
[5,]   44  168  372  656
[6,]   55  210  465  820

$B
     [,1] [,2] [,3] [,4]
[1,]    0    0    0    0
[2,]  275  396  539  704
[3,]  550  792 1078 1408
[4,]  825 1188 1617 2112
[5,] 1100 1584 2156 2816
[6,] 1375 1980 2695 3520

Because the vectors in f are of length 4, we use outer(x, ti), which results in a 4X6 matrix, This allows y to be properly multiplied over the corresponding elements using recycling, but requires a t transpose of the result.

This can also be written with the %o% operator as

Map(function(x, y) t(x %o% ti * y), d, f)

Upvotes: 3

akrun
akrun

Reputation: 887691

One option is

library(tidyverse)
ti %>%
     map(~f*d *.)  %>%
     transpose %>%
     map(~do.call(rbind, .))
#$A
#     [,1] [,2] [,3] [,4]
#[1,]    0    0    0    0
#[2,]   11   42   93  164
#[3,]   22   84  186  328
#[4,]   33  126  279  492
#[5,]   44  168  372  656
#[6,]   55  210  465  820

#$B
#     [,1] [,2] [,3] [,4]
#[1,]    0    0    0    0
#[2,]  275  396  539  704
#[3,]  550  792 1078 1408
#[4,]  825 1188 1617 2112
#[5,] 1100 1584 2156 2816
#[6,] 1375 1980 2695 3520

Upvotes: 1

Related Questions