R:将数据帧转换为矩阵

时间:2015-08-14 11:06:00

标签: r matrix

我有一个写入csv file的矩阵。

enter image description here

我试图读取文件并将数据作为矩阵。我使用了as.matrix和data.matrix函数。但是,我无法将数据作为矩阵加载。 我的目标是使用此距离矩阵进行分层聚类 enter image description here enter image description here

1 个答案:

答案 0 :(得分:5)

我们可以使用read.csv来阅读.csv文件,将第一列设置为行名row.names=1),然后转换为matrixas.matrix )应该工作正常。

  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

或者@RHertel在评论中提到,我们可以在一个步骤中结合使用

  as.matrix(read.csv('Test_Matrix.csv', row.names=1))