[英]How to insert colnames and rownames onto a matrix?
我有一個包含 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
我想將列名和行名插入到矩陣中。 這些存在於文本文件中。 此文本文件的總行數為 5777。
head(file.txt)
A1
B2
C3
D4
E5
F6
G7
我怎樣才能在矩陣中插入列表(行名和列名),所以它看起來像這樣
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
我試過了
#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)
我沒有收到任何錯誤,但 output 完全錯誤,沒有插入 header 或行。
請參閱下面的代碼:
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")
然后你可以通過rownames(test) <-...
您可以這樣設置 dimnames:
m <- matrix(1:4,,2)
dimnames(m) <- list(c('A', 'B'), c('Alice', 'Bob'))
output:
## > m
Alice Bob
A 1 3
B 2 4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.