Tom
Tom

Reputation: 2341

Adding a column name to a table column without a name

I have data as follows:

dat <- structure(c(TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 
            TRUE), dim = c(3L, 3L), dimnames = list(c("A", "B", 
                                                      "C"), c("[0,25) D", "[0,25) E", NA)))

name_vec <- "[0,25) F"

What I want to do is the following:

colnames(dat )[length(dat )] <- name_vec[i]

But this gives the error:

 Error in dimnames(x) <- dn : 
  length of 'dimnames' [2] not equal to array extent

I am failing to understand why this does not work or what the error means.

Any help would be appreciated.

Upvotes: 0

Views: 60

Answers (1)

benson23
benson23

Reputation: 19097

I guess you want to do the following:

colnames(dat)[ncol(dat)] <- name_vec

  [0,25) D [0,25) E [0,25) F
A     TRUE     TRUE     TRUE
B    FALSE     TRUE     TRUE
C     TRUE     TRUE     TRUE

Since your dat is a matrix, length would return the number of elements in the matrix, which is 9 in your case. However, you do not have 9 columns, therefore it gives you the error.

class(dat)
[1] "matrix" "array" 

length(dat)
[1] 9

ncol(dat)
[1] 3

So the correct function to use should be ncol.

Upvotes: 4

Related Questions