主要功能类似于以下代码:
#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)
但它看起来真的非常愚蠢。任何人都可以提供更简单的方式吗?
谢谢。
答案 0 :(得分:5)
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
答案 1 :(得分:3)
我猜expand.grid
就是你要找的。 p>
getAllCombinations <- function(a,b,r=3,col = 4){
# this is the key
g <- expand.grid(a,b)
matrix(g$Var1*g$Var2,r,col)
}
# call the function
getAllCombinations(x,y)
编辑:
在这里要成为一名运动员。到目前为止,我自己的解决方案实际上是最慢的,尽管它比许多lapply
和匿名函数更容易理解。如果您对它进行基准测试:@ExperimenteR不仅赢得了易于阅读的比赛,还赢得了比赛......
# performance
library(rbenchmark)
benchmark(
outer(x, y, f),
getAllCombinations(x,y),
vrajs(),
replications = 10000
)
请注意,我将@vrajs解决方案变成了一个保持公平的功能。
答案 2 :(得分:2)
我希望以下内容对您有用
#x is a's value group
x <- c(1,2,3,4)
#y is b's value group
y <- c(4,5,6)
matrix(unlist(lapply(1:length(x),
function(a){
lapply(1:length(y),
function(b){x[a]*y[b]})})),
ncol = length(y), byrow = TRUE)
[,1] [,2] [,3]
[1,] 4 5 6
[2,] 8 10 12
[3,] 12 15 18
[4,] 16 20 24
更新:代码说明