[R] name ONLY one column // empty.dimnames() in 'sfsmisc'

Martin Maechler maechler at stat.math.ethz.ch
Wed Sep 29 10:16:53 CEST 2010


>>>>> "IC" == Ivan Calandra <ivan.calandra at uni-hamburg.de>
>>>>>     on Mon, 27 Sep 2010 16:59:31 +0200 writes:

    IC> Hi,
    IC> I'm not sure it's even possible (and if it is I don't know how, but I'm 
    IC> no expert).

yes it is possible (in some way), see below.

    IC> But I think it doesn't make much sense to have only one named column. 
    IC> Just give it a vector:
    IC> vect_names <- c("myname1", "myname2", "myname3")
    IC> colnames(my_matrix) <- vect_names

yes, exactly,  ... but read on

    IC> HTH,
    IC> Ivan

    IC> Le 9/27/2010 10:26, Lorenzo Cattarino a écrit :
    >> Hi R-users
    >> 
    >> I can not change the name of one column only of my matrix.
    >> 
    >> my_matrix <- matrix (1:12,ncol=3)

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

Just read ... and maybe re-read this error message. It is
exactly on target:

The colnames  "are the" dimnames(.)[2] and they have the wrong length.
{ I'm too often disappointed that many R users read only the
  first, or actually the zero-th word of the 'very fine' error
  messages that we provide you with (most of the time):
  Such useRs only read up to "Error"  .. and are put off, saying
  "It does not work" or  "Why can't I ..."  or  "...".
}

Now back to the original question:
What you want is to give <empty> column names to all but the
first column.

  mat <- matrix(1:12, 3)
  colnames(mat) <- c("myname", "", "")

And a note: giving empty column- and row-names is sometimes
desirable if just for printing.
For that reason, our  'sfsmisc' CRAN package has contained the function
empty.dimnames() for many years now (actually longer than R
exists; we had it as an S+ function in our "goodies"
collection). Excerpt from its help page:

> empty.dimnames             package:sfsmisc             R Documentation

> Empty Dimnames of an Array.

> Description:
>      `Remove' all dimension names from an array for compact printing.

> Usage:
>      empty.dimnames(a)
     
> Arguments:
>        a: an ‘array’, especially a matrix.

> Value:
>      Returns ‘a’ with its dimnames replaced by empty character strings.

> Author(s):
>      Bill Venables / Martin Maechler, Sept 1993.


and here the examples we provide:

> example(empty.dimnames)

empty.> empty.dimnames(diag(5)) # looks much nicer
          
 1 0 0 0 0
 0 1 0 0 0
 0 0 1 0 0
 0 0 0 1 0
 0 0 0 0 1

empty.> (a <- matrix(-9:10, 4,5))
     [,1] [,2] [,3] [,4] [,5]
[1,]   -9   -5   -1    3    7
[2,]   -8   -4    0    4    8
[3,]   -7   -3    1    5    9
[4,]   -6   -2    2    6   10

empty.> empty.dimnames(a) # nicer, right?
              
 -9 -5 -1 3  7
 -8 -4  0 4  8
 -7 -3  1 5  9
 -6 -2  2 6 10
>



More information about the R-help mailing list