Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Converting a data frame into a matrix

Tags:

r

matrix

I have a matrix written to a csv file.

enter image description here

I'm trying to read the file and get the data as a matrix. I have used as.matrix and data.matrix functions. However I'm unable to load the data as a matrix. My goal is to use this distance matrix for hierarchical clustering.
enter image description here enter image description here

like image 394
SriniShine Avatar asked Oct 27 '25 09:10

SriniShine


1 Answers

We can use read.csv to read the .csv file, set the first column as row names (row.names=1), and converting to matrix (as.matrix) should work fine.

  d1 <- read.csv('Test_Matrix.csv', row.names=1)
  m1 <- as.matrix(d1)
  m1
  #  A B C D
  #A 0 1 2 3
  #B 1 0 4 5
  #C 2 4 0 6
  #D 3 5 6 0
  is.matrix(m1)
  #[1] TRUE

Or as @RHertel mentioned in the comments, we can combine both in a single step

  as.matrix(read.csv('Test_Matrix.csv', row.names=1))
like image 56
akrun Avatar answered Oct 29 '25 22:10

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!