2012-02-20 97 views
14

我有這樣的代碼在R:矩陣顯示沒有行名和列名?

seq1 <- seq(1:20) 
mat <- matrix(seq1, 2) 

,其結果是:

 [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] 
[1,] 1 3 5 7 9 11 13 15 17 19 
[2,] 2 4 6 8 10 12 14 16 18 20 

是否R 5具有一個選項,以抑制列名稱和行名稱的顯示讓我沒有得到[,1] [,2]等等?

+0

你在'R'控制檯是什麼意思?或者當你從'R'導出? – Justin 2012-02-20 18:56:41

+0

另請注意,在R中,在語句結尾不需要分號。 'mat'不是命令。我假設你的意思是'矩陣(seq1,2)',因爲你的命令不起作用... – Dason 2012-02-20 19:09:07

回答

14

如果您想保留維度的名稱,但只是不打印出來,你可以定義一個新的打印功能。

print.matrix <- function(m){ 
write.table(format(m, justify="right"), 
      row.names=F, col.names=F, quote=F) 
} 

> print(mat) 
1 3 5 7 9 11 13 15 17 19 
2 4 6 8 10 12 14 16 18 20 
+2

我會在父函數中使用省略號,並將它傳遞給格式函數,所以可用的選項格式可以通過print.matrix訪問,即scientific = FALSE等。 – 2015-06-02 06:27:15

4

這適用於矩陣:

seq1 <- seq(1:20) 
mat <- matrix(seq1, 2) 

dimnames(mat) <-list(rep("", dim(mat)[1]), rep("", dim(mat)[2])) 
mat 
1

通過Fojtasek解決方案可能是最好的,但這裏是另一個使用sprintf的替代。

print.matrix <- function(x,digits=getOption('digits')){ 
    fmt <- sprintf("%% .%if",digits) 
    for(r in 1:nrow(x)) 
    writeLines(paste(sapply(x[r,],function(x){sprintf(fmt,x)}),collapse=" ")) 
} 
2

有,也?prmatrix

prmatrix(mat, collab = rep_len("", ncol(mat)), rowlab = rep_len("", ncol(mat))) 
#       
# 1 3 5 7 9 11 13 15 17 19 
# 2 4 6 8 10 12 14 16 18 20