如何简化这个程序? [英] How to simplify this programme?

查看:157
本文介绍了如何简化这个程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  #f是一个具有两个参数并返回一个值的函数: 
f < - 函数(a,b){
a * b
}

#x是a的值组
x < - c(1, 2,3,4)
#y是b的价值组
y< - c(4,5,6)

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

  m <-c(NULL)
for(a in x) (b,y){
m < - c(m,c(a,b))
}
}
m < - 矩阵(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


The main function is like the following code:

#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)

I want to get all the possible values of f(x, y), and the result should be a matrix to be clear. Now I am using the for loop:

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

But it seems really very very silly.Can any one provide a simpler way?

Thank you.

解决方案

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

这篇关于如何简化这个程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆