R:使用嵌套应用在两个数据框中的所有列组合上运行
R: function on all column combinations from two data frames using nested apply
给定两个列数相同的矩阵。
m1 <- matrix(1:12, ncol=3)
m2 <- matrix(10:2, ncol=3)
假设我有一个函数,它接受两个向量并执行类似于每个向量的乘积 min(玩具示例)的操作:
fun <- function(v1, v2)(min(v1)*min(v2))
我无法理解如何使用两个嵌套的应用调用对所有列组合执行该函数。
在 m1 和第一列上使用 apply 就像:
apply(m1, 2, fun, m2[,1])
我坚持循环遍历 m2 的所有列,例如:
m3<-matrix(NA, ncol=3, nrow=3)
for(c in 1:ncol(m2)){
m3[,c] <- apply(m1, 2, fun, m2[,c])
}
这给出了
> m3
[,1] [,2] [,3]
[1,] 10 9 8
[2,] 50 45 40
[3,] 90 81 72
那么如何将此循环构建为一个应用程序?
编辑:代码有错误 - 抱歉。见编辑
我会在这里使用 mapply
,并稍微更改函数,使其传递索引而不是实际的列:
m1 <- matrix(1:12, ncol=3)
m2 <- matrix(10:2, ncol=3)
fun <- function(i1, i2) (min(m1[,i1])*min(m2[,i2]))
res <- matrix(mapply(fun, rep(1:3, times=3), rep(1:3, each=3)), ncol=3)
这是你想要的吗?
如果你有兴趣使用嵌套apply
,我们可以试试
apply(m1, 2, function(x) apply(m2, 2, function(y) min(x) * min(y)))
# [,1] [,2] [,3]
#[1,] 8 40 72
#[2,] 5 25 45
#[3,] 2 10 18
由于您已经定义了函数,
apply(m1, 2, function(x) apply(m2, 2, fun, x))
会更简单。
我们可以使用向量化函数更轻松地做到这一点,例如 outer
colMins
(来自 matrixStats
)
library(matrixStats)
outer(colMins(m1), colMins(m2))
# [,1] [,2] [,3]
#[1,] 8 5 2
#[2,] 40 25 10
#[3,] 72 45 18
给定两个列数相同的矩阵。
m1 <- matrix(1:12, ncol=3)
m2 <- matrix(10:2, ncol=3)
假设我有一个函数,它接受两个向量并执行类似于每个向量的乘积 min(玩具示例)的操作:
fun <- function(v1, v2)(min(v1)*min(v2))
我无法理解如何使用两个嵌套的应用调用对所有列组合执行该函数。 在 m1 和第一列上使用 apply 就像:
apply(m1, 2, fun, m2[,1])
我坚持循环遍历 m2 的所有列,例如:
m3<-matrix(NA, ncol=3, nrow=3)
for(c in 1:ncol(m2)){
m3[,c] <- apply(m1, 2, fun, m2[,c])
}
这给出了
> m3
[,1] [,2] [,3]
[1,] 10 9 8
[2,] 50 45 40
[3,] 90 81 72
那么如何将此循环构建为一个应用程序?
编辑:代码有错误 - 抱歉。见编辑
我会在这里使用 mapply
,并稍微更改函数,使其传递索引而不是实际的列:
m1 <- matrix(1:12, ncol=3)
m2 <- matrix(10:2, ncol=3)
fun <- function(i1, i2) (min(m1[,i1])*min(m2[,i2]))
res <- matrix(mapply(fun, rep(1:3, times=3), rep(1:3, each=3)), ncol=3)
这是你想要的吗?
如果你有兴趣使用嵌套apply
,我们可以试试
apply(m1, 2, function(x) apply(m2, 2, function(y) min(x) * min(y)))
# [,1] [,2] [,3]
#[1,] 8 40 72
#[2,] 5 25 45
#[3,] 2 10 18
由于您已经定义了函数,
apply(m1, 2, function(x) apply(m2, 2, fun, x))
会更简单。
我们可以使用向量化函数更轻松地做到这一点,例如 outer
colMins
(来自 matrixStats
)
library(matrixStats)
outer(colMins(m1), colMins(m2))
# [,1] [,2] [,3]
#[1,] 8 5 2
#[2,] 40 25 10
#[3,] 72 45 18