[英]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 如果我用数据帧替换矢量e
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? 所以d和f是按元素操作的?
I know that d and f will always be of identical dimensions. 我知道d和f总是具有相同的尺寸。
Update: 更新:
Also, is there a solution that would work with a more complicated function like d * exp(ti * f) instead of d * ti * f? 此外,是否有一个解决方案可以使用更复杂的函数,如d * exp(ti * f)而不是d * ti * f?
In base R with Map
and outer
, you can do 在带有
Map
和outer
基础R中,你可以做到
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. 因为f中的向量长度为4,所以我们使用
outer(x, ti)
,这导致4X6矩阵。这允许y使用循环在相应的元素上正确相乘,但需要对结果进行t
转置。
This can also be written with the %o%
operator as 这也可以使用
%o%
运算符编写
Map(function(x, y) t(x %o% ti * y), d, f)
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.