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.
To create a matrix in R you need to use the function called matrix(). The arguments to this matrix() are the set of elements in the vector. You have to pass how many numbers of rows and how many numbers of columns you want to have in your matrix. Note: By default, matrices are in column-wise order.
A matrix can be created in R using the matrix() function. For example, the following code will produce a 3 by 3 matrix: mtx <- matrix(3:11, nrow = 3, ncol = 3) . Moreover, it is possible to combine vectors to create a matrix.
Naming Rows and Columns of a Matrix in R Programming – rownames() and colnames() Function. rownames() function in R Language is used to set the names to rows of a matrix.
You can use the apply() function to apply a function to each row in a matrix or data frame in R. where: X: Name of the matrix or data frame. MARGIN: Dimension to perform operation across.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With