简体   繁体   English

如何将列名和行名插入矩阵?

[英]How to insert colnames and rownames onto a matrix?

I have a square matrix that has 5777 columns and rows.我有一个包含 5777 列和行的方阵。

head(data)
1.3 4.5 6 7 8.9 0 7.6
4.5 6.7 8 9 0.1 8 7.2
4.5 6 7 8.9 0.1 8 8.3
6.7 8 9 0.1 7.9 6.0 5
2.4 6.7 8 3 0.1 8 7.4 
8 9 0.1 7.9 6.0 5 5.6

I want to insert column names and row names onto the matrix.我想将列名和行名插入到矩阵中。 These exist in a text file.这些存在于文本文件中。 The total number of rows this text-file has is 5777.此文本文件的总行数为 5777。

head(file.txt)

A1
B2
C3
D4
E5
F6
G7

How can I insert the list on the matrix (row names and column names) so it looks like this我怎样才能在矩阵中插入列表(行名和列名),所以它看起来像这样

A1 B2 C3 D4 E5 F6 G7
B2 1.3 4.5 6 7 8.9 0 7.6
C3 4.5 6.7 8 9 0.1 8 7.2
D4 4.5 6 7 8.9 0.1 8 8.3
E5 6.7 8 9 0.1 7.9 6.0 5
F6 2.4 6.7 8 3 0.1 8 7.4 
G7 8 9 0.1 7.9 6.0 5 5.6

I have tried我试过了

#read in row names and column names  
header <- read.table("file.txt")

#read in matrix
data <- read.table("armlympho_matrix.ld")

#set the row names and column names in matrix 
rownames(data) <- header[[1]]
colnames(data) <- header[[1]]
 
write.table(data, '/data/genome/h8/matrix_withheader.ld', row.names=FALSE, quote=FALSE)

I get no error but the output is completely wrong with no header or row inserted.我没有收到任何错误,但 output 完全错误,没有插入 header 或行。

See code below:请参阅下面的代码:

text <- "1.3 4.5 6 7 8.9 0 7.6
4.5 6.7 8 9 0.1 8 7.2
4.5 6 7 8.9 0.1 8 8.3
6.7 8 9 0.1 7.9 6.0 5
2.4 6.7 8 3 0.1 8 7.4 
8 9 0.1 7.9 6.0 5 5.6"

test <- read.table(textConnection(text), header=FALSE, sep="")  
test <- as.matrix(test)  
colnames(test) <-  c("A1", "B2", "C3", "D4", "E5", "F6", "G7")

Then you can complete yourself by rownames(test) <-...然后你可以通过rownames(test) <-...

you can set the dimnames this way:您可以这样设置 dimnames:

m <- matrix(1:4,,2)
dimnames(m) <- list(c('A', 'B'), c('Alice', 'Bob'))

output: output:

## > m
  Alice Bob
A     1   3
B     2   4

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

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