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.
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.
Convert Data Frame to Matrix in RYou can load your dataframe into a matrix and do the matrix operations on it.
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.
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]))
)
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