Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a matrix from a function and two numeric data frames

Tags:

r

I'm trying to create matrices of various distance/association functions in R. I have a function similar to cor that gives the association between two vectors. Now I want to take a dataframe (or matrix) of numeric vectors, something like mtcars, and create a matrix from the function and data frame. I thought this is what outer is for but am not getting it to work. Here's an attempt using cor and mtcars.

cor(mtcars$mpg, mtcars$cyl)  #a function that gives an association between two vectors                  
outer(mtcars, mtcars, "cor") #the attempt to create a matrix of all vectors in a df

Yes I know that cor can do this directly, let's pretend it can't. that cor just finds correlations between two vectors.

So the final goal would be to get the matrix you get from cor(mtcars).

Thank you in advance.

like image 903
Tyler Rinker Avatar asked Mar 28 '12 23:03

Tyler Rinker


People also ask

How do you create a matrix from a data frame?

Convert a Data Frame into a Numeric Matrix in R Programming – data. matrix() Function. data. matrix() function in R Language is used to create a matrix by converting all the values of a Data Frame into numeric mode and then binding them as a matrix.

Can Dataframe be converted into matrix in R?

Convert Data Frame to Matrix in RYou can load your dataframe into a matrix and do the matrix operations on it.

What is difference between matrix and Dataframes?

Both represent 'rectangular' data types, meaning that they are used to store tabular data, with rows and columns. The main difference, as you'll see, is that matrices can only contain a single class of data, while data frames can consist of many different classes of data.


1 Answers

You can use outer with a function that takes column names or column numbers as arguments.

outer(
  names(mtcars), 
  names(mtcars), 
  Vectorize(function(i,j) cor(mtcars[,i],mtcars[,j]))
)
like image 185
Vincent Zoonekynd Avatar answered Sep 24 '22 00:09

Vincent Zoonekynd