简体   繁体   English

如何将数据帧作为矩阵读取?

[英]how to read a dataframe as a matrix?

I want to read the csv file as a matrix, and the matrix is numeric. 我想将csv文件作为矩阵读取,矩阵是数字。 The followwing is my code 跟随是我的代码

1, read the data 1,读取数据

mydata<-read.csv("mydata.csv", header = TRUE, sep=',', check.names = FALSE)
str(mydata)

2, transform as numeric data 2,转换为数字数据

mydata_1<-data.matrix(mydata)
str(mydata_1)

For the first step, the output is fine 第一步,输出很好 见pic1

but for the second step, when I want to transform the dataframe as a numeric matrix, the output is changed to be as follows. 但是对于第二步,当我想将数据帧转换为数字矩阵时,输出将更改为如下所示。 See that the rownames and the column names have been changed, and the cell values are also not true, which are not wanted. 请注意,rownames和列名称已更改,并且单元格值也不是true,这是不需要的。 见pic2

I also tried the following syntax, but it produced the same result as above. 我也尝试了以下语法,但它产生了与上面相同的结果。

mydata_1<-sapply(mydata, as.numeric)

and here is the link of my data file link of mydata 这是我的mydata数据文件链接的链接

Any suggestion is appreciated. 任何建议表示赞赏。

This is because you have several data types (factor, num), and a matrix can only store one single data type. 这是因为您有多种数据类型(factor,num),而矩阵只能存储一种数据类型。 I'd suggest you remove the first column to have only numerics: 我建议你删除第一列只有数字:

mydata_1<-data.matrix(mydata[,-1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM