简体   繁体   中英

How to build a matrix in r by using “apply” and passing vectors as arguments to a custom function

I would like to create a matrix as follows and am not sure if I should be using the apply family of functions or some other matrix function (I want to avoid using nested for loops):

DATA INPUTS:

sequence <- seq(5, 25, 5)
dataset <- c(3, 6, 8, 3, 4, 5, 6, 2, 10, 4)

CUSTOM FUNCTION:

calculation <- function(foo, bar) {
    result <- bar * foo * 0.5
    return(result)
}

GOAL:

str(goal)
num [1:10, 1:5] 7.5 15 20 7.5 10 12.5 15 5 25 10 ...
goal
      [,1] [,2] [,3] [,4]  [,5]
 [1,]  7.5   15 22.5   30  37.5
 [2,] 15.0   30 45.0   60  75.0
 [3,] 20.0   40 60.0   80 100.0
 [4,]  7.5   15 22.5   30  37.5
 [5,] 10.0   20 30.0   40  50.0
 [6,] 12.5   25 37.5   50  62.5
 [7,] 15.0   30 45.0   60  75.0
 [8,]  5.0   10 15.0   20  25.0
 [9,] 25.0   50 75.0  100 125.0
[10,] 10.0   20 30.0   40  50.0

It seems that outer() was the function I was looking for (ie the "outer product of arrays"). The order of input arrays to outer() is important to the structure of the resulting matrix. Thank you thelatemail and Ketil BT

CORRECT VERSION:

goal.matrix <- outer(dataset,sequence, FUN=calculation)

Note: if the order of input arrays to outer() is reversed, the resulting matrix is simply the transposed version of goal.matrix.

transposed.goal <- outer(sequence, dataset, FUN=calculation)
transposed.goal

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]  7.5   15   20  7.5   10 12.5   15    5   25    10
[2,] 15.0   30   40 15.0   20 25.0   30   10   50    20
[3,] 22.5   45   60 22.5   30 37.5   45   15   75    30
[4,] 30.0   60   80 30.0   40 50.0   60   20  100    40
[5,] 37.5   75  100 37.5   50 62.5   75   25  125    50

goal.matrix <- t(transposed.goal)
goal.matrix

       [,1] [,2] [,3] [,4]  [,5]
 [1,]  7.5   15 22.5   30  37.5
 [2,] 15.0   30 45.0   60  75.0
 [3,] 20.0   40 60.0   80 100.0
 [4,]  7.5   15 22.5   30  37.5
 [5,] 10.0   20 30.0   40  50.0
 [6,] 12.5   25 37.5   50  62.5
 [7,] 15.0   30 45.0   60  75.0
 [8,]  5.0   10 15.0   20  25.0
 [9,] 25.0   50 75.0  100 125.0
[10,] 10.0   20 30.0   40  50.0

Do you realize you have essentially described the relevant nested for-loop? So unless you really want to use apply, you're actually done.

That is,

goal <- matrix(NA, 1000, 166)
for(i in 1:nrow(goal)){
  for(j in 1:ncol(goal)){
    goal[i, j] <- dataset[i] * sequence[j] * 0.004
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM