当FUN产生多个值时,有没有办法将`outer`用于两个向量

时间:2016-08-16 03:21:55

标签: r list matrix

我有这样的功能

myfun <- function(x, y){
  c(x, y, x+y, x*y)
}

我想在函数outer中使用它,就像这样

vmyfun <- Vectorize(myfun)

outer(1:10, 2:5,vmyfun)

我希望结果是一个包含4个矩阵的列表

  [[1]]
      [,1] [,2] [,3] [,4]
 [1,]    1    1    1    1
 [2,]    2    2    2    2
 [3,]    3    3    3    3
 [4,]    4    4    4    4
 [5,]    5    5    5    5
 [6,]    6    6    6    6
 [7,]    7    7    7    7
 [8,]    8    8    8    8
 [9,]    9    9    9    9
[10,]   10   10   10   10

[[2]]
      [,1] [,2] [,3] [,4]
 [1,]    2    3    4    5
 [2,]    2    3    4    5
 [3,]    2    3    4    5
 [4,]    2    3    4    5
 [5,]    2    3    4    5
 [6,]    2    3    4    5
 [7,]    2    3    4    5
 [8,]    2    3    4    5
 [9,]    2    3    4    5
[10,]    2    3    4    5

[[3]]
      [,1] [,2] [,3] [,4]
 [1,]    3    4    5    6
 [2,]    4    5    6    7
 [3,]    5    6    7    8
 [4,]    6    7    8    9
 [5,]    7    8    9   10
 [6,]    8    9   10   11
 [7,]    9   10   11   12
 [8,]   10   11   12   13
 [9,]   11   12   13   14
[10,]   12   13   14   15

[[4]]
      [,1] [,2] [,3] [,4]
 [1,]    2    3    4    5
 [2,]    4    6    8   10
 [3,]    6    9   12   15
 [4,]    8   12   16   20
 [5,]   10   15   20   25
 [6,]   12   18   24   30
 [7,]   14   21   28   35
 [8,]   16   24   32   40
 [9,]   18   27   36   45
[10,]   20   30   40   50

有没有办法实现这个?谢谢你们。

更新: 我为这个问题做了一个坏榜样。我真正想要的比我提供的示例结果复杂得多。 我不想更改函数myfun。这是一个新的例子。它是一个获得不同阈值的垫子总和的函数。

myfun2 <- function(x, y){
  mat <- matrix(data = rexp(x, rate = y), nrow = 10, ncol = 20)

  sapply(seq(from = 0, to = max(mat), length.out = 100), function(x){
    mat[mat < x] <- 0
    sum(mat)})
}


> myfun2(10,15)
  [1] 10.023527 10.023527 10.023527 10.023527 10.023527 10.023527 10.023527 10.023527  9.893362
 [10]  9.893362  9.893362  9.893362  9.893362  9.893362  9.893362  9.893362  9.893362  9.893362
 [19]  9.893362  9.893362  9.893362  9.893362  9.893362  9.893362  9.893362  9.893362  9.893362
 [28]  9.893362  9.893362  9.893362  9.353354  9.353354  9.353354  9.353354  9.353354  9.353354
 [37]  9.353354  9.353354  9.353354  9.353354  9.353354  9.353354  9.353354  8.563003  8.563003
 [46]  8.563003  8.563003  8.563003  8.563003  7.673577  7.673577  7.673577  6.729326  6.729326
 [55]  6.729326  6.729326  6.729326  6.729326  6.729326  6.729326  6.729326  6.729326  5.590193
 [64]  5.590193  5.590193  5.590193  4.385858  4.385858  4.385858  3.113081  1.828594  1.828594
 [73]  1.828594  1.828594  1.828594  1.828594  1.828594  1.828594  1.828594  1.828594  1.828594
 [82]  1.828594  1.828594  1.828594  1.828594  1.828594  1.828594  1.828594  1.828594  1.828594
 [91]  1.828594  1.828594  1.828594  1.828594  1.828594  1.828594  1.828594  1.828594  1.828594
[100]  1.828594

此函数将为给定xy创建长度为100的向量。 我想像这样使用它。

vmyfun2 <- Vectorize(myfun2)

outer(1:15, 1:10,vmyfun2)

,结果应该是100矩阵的列表

0 个答案:

没有答案