r - 如何简化这个程序?

标签 r function loops for-loop matrix

主要功能如下代码:

#f is a function that has two parameters and returns one value:
f <- function(a, b) {
   a * b
}

#x is a's value group
x <- c(1,2,3,4)
#y is b's value group
y <- c(4,5,6)

我想得到f(x, y)所有可能的值,结果应该是一个矩阵才能清楚。现在我正在使用 for 循环:

m <- c(NULL)
for (a in x) {
   for (b in y) {
       m <- c(m, c(a, b))
    }
}
m <- matrix(m, 3, 4)

但这看起来真的非常非常傻。谁能提供更简单的方法?

谢谢。

最佳答案

outer(x, y, f)
#     [,1] [,2] [,3]
#[1,]    4    5    6
#[2,]    8   10   12
#[3,]   12   15   18
#[4,]   16   20   24
outer(y, x, f)
#     [,1] [,2] [,3] [,4]
#[1,]    4    8   12   16
#[2,]    5   10   15   20
#[3,]    6   12   18   24

关于r - 如何简化这个程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29272337/

相关文章:

r - 如何在 R Markdown 中删除图像上方和下方的空白?

c - C中的递归函数是如何工作的

c - 如何将字符串转换为 double 浮点值?

javascript - 如何全局重写 HTMLElement 原生方法?

arrays - 如何在 MATLAB 中的 for 循环内创建比率数组?

vba - Excel VBA : Restart Loop Counter

r - 我是否需要对 randomForest(R 包)的数据进行标准化(或缩放)?

html - 将颜色主题更改为 HTML markdown

R Shiny : How to write loop for observeEvent

javascript - 使用串联和传递的参数循环遍历数组