I have a square matrix that has 5777 columns and rows.
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.
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.
CodePudding user response:
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) <- ...
CodePudding user response:
you can set the dimnames this way:
m <- matrix(1:4,,2)
dimnames(m) <- list(c('A', 'B'), c('Alice', 'Bob'))
output:
## > m
Alice Bob
A 1 3
B 2 4