Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R creating a matrix using a formula of the rows and columns

Tags:

r

matrix

apply

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.

like image 613
Hugh Avatar asked Sep 26 '12 06:09

Hugh


People also ask

How do you make a column or row matrix in R?

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.

How do I create a data matrix in R?

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.

How do you name rows and columns in a matrix in R?

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.

How do I apply the same function to all rows and columns of a matrix in R?

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.


1 Answers

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
like image 58
Roland Avatar answered Oct 21 '22 07:10

Roland