'dimnames error'取决于填充顺序的colnames

时间:2017-03-03 15:28:02

标签: r matrix

这段代码很好用:

MATRIX_RESULT_CSV <- matrix(NA,nrow=1,ncol=5)
colnames(MATRIX_RESULT_CSV)[3:5]   <- c("3", "4", "5")
colnames(MATRIX_RESULT_CSV)[1:2]   <- c("1", "2")

然而,当首先填充furst列时,它会产生'dimname error':

MATRIX_RESULT_CSV <- matrix(NA,nrow=1,ncol=5)
colnames(MATRIX_RESULT_CSV)[1:2]   <- c("1", "2")
colnames(MATRIX_RESULT_CSV)[3:5]   <- c("3", "4", "5")

Error in `colnames<-`(`*tmp*`, value = c("1", "2")) : 
  length of 'dimnames' [2] not equal to array extent

我正在看下面的原因。

1 个答案:

答案 0 :(得分:-1)

不确定其根本原因,但其中很有效:

MATRIX_RESULT_CSV <- matrix(NA,nrow=1,ncol=5)
colnames(MATRIX_RESULT_CSV) = rep(NA, ncol(MATRIX_RESULT_CSV))
colnames(MATRIX_RESULT_CSV)[1:2] = c("1","2")