简体   繁体   English

将data.frame转换为矩阵(R),rownames()错误

[英]data.frame into matrix (R) , rownames() error

I have a data.frame ("data.csv") of 93 x 28 I want to convert into matrix for further plotting, it looks like this: 我有一个93 x 28的data.frame(“ data.csv”),我想转换成矩阵以作进一步绘制,它看起来像这样:

SYMBOL  BT.20   CAL.51  MDA.MB.436  BT.549
A   3.039   4.908   3.865   3.818
B   4.349   5.399   6.071   5.313
C   7.509   8.091   6.48    6.660
D   3.429   4.394   3.622   3.873
E   3.369   6.716   3.557   3.346

the code 编码

data <- read_csv("data.csv")
rnames <- data[,1]              # assign labels in column 1 to "rnames"  
mat_data <- data.matrix(data[,2:28])  # transform column 2 - end into a matrix
rownames(mat_data) <- rnames                  # assign row names

produces 产生

ERROR: Error in `rownames<-`(`*tmp*`, value = list(SYMBOL = c("A", "B",  : 
  length of 'dimnames' [1] not equal to array extent

column 1 doesn't have duplicate names or missing values 第1列没有重复的名称或缺少值

edit: with read.csv() instead, it works just fine 编辑:使用read.csv()代替,它可以正常工作

The error is saying that the value being assigned to the rownames is a list and the "length" of a list with a single vector in it is 1, rather than the length of the vector. 错误是指分配给行名的值是一个列表,并且其中包含单个向量的列表的“长度”为1,而不是向量的长度。 I'm not able to say why that should be happening since the usual behavior is for the "[" function to "drop" single columns into atomic vectors. 我无法说出为什么会发生这种情况,因为通常的行为是使[[]函数将单个列“拖放”到原子向量中。 Like you, I would have expected rnames to be an atomic vector of length 39, but it appears you need to use this instead: 像您一样,我希望rnames是长度为39的原子向量,但看来您需要使用它:

rownames(mat_data) <- unlist( rnames )              # assign row names

Rich and Apom have better eyes than I do. Rich和Apom比我有更好的眼睛。 The read_csv function is producing an object with a different class and associated extraction function than would have read.csv . 该read_csv函数产生具有不同的类和除将具有相关联的提取功能的对象read.csv Since you are in the "hadleyverse", you therefore should use this: 由于您处于“ hadleyverse”中,因此您应该使用以下代码:

 rnames <- data[[1]]

The tibble -classed objects have a different version of the [ -function than do data.frames. tibble -classed对象有不同的版本的[ -function不是做data.frames。 The [[ -function appears to act the same for both classes. [[ -函数对于这两个类似乎作用相同。

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

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