Reputation: 16090
How would I create a matrix (the normal sense, not the R sense) where the (i,j) entry is a function of i and j? I think it involves apply()
but I can't seem to work out how to use it.
Say if I have columns x1, x2, ... and rows y1,y2 where the x1 and y1 are R objects and I want to build a table/matrix where the entry is a function of xi and yj for each i and j.
Sorry if this has been answered elsewhere.
Upvotes: 7
Views: 3400
Reputation: 132676
I'm not sure I understand the entire question. I will just answer the question in the first sentence:
fun <- function(i,j) i*j
rows <- 1:5
cols <- 1:3
outer(rows,cols,FUN=fun)
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 2 4 6
[3,] 3 6 9
[4,] 4 8 12
[5,] 5 10 15
Upvotes: 11