[R] Weird behavior with names()

Thomas Lumley thomas at biostat.washington.edu
Wed Jul 14 21:38:50 CEST 1999

On Wed, 14 Jul 1999, Christian Posse wrote:

> Dear R fellows,
> Is the following a feature or a bug of names() ??
> It does  not seem to be reported as a bug in the R Bug Tracking System.

Neither. It is a side effect of a feature of matrices. 

Consider the following three ways to get at the (1,1) element of xy
	names(xy[,1][1])  #returns name of row 1
	names(xy[1,][1])  #returns name of column 1
	names(xy[1,1])	  #returns NULL

What is happening is that xy[1,1] is a 1x1 matrix, which is coerced by
default to a scalar, which does not have a names attribute (since it's not
clear whether it should be the row 1 or column 1 name)

On the other hand xy[,1][1] is computed by coercing xy[,1] to a vector,
retaining the row names of xy as the names, and then taking the first
element, whose name is the name of the first row of xy. Similarly,
names(xy[1,][1]) is the name of the first column of xy.  In your example
there weren't any column names so it was less obvious.

Thomas Lumley
Assistant Professor, Biostatistics
University of Washington, Seattle

r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch

More information about the R-help mailing list