Do the following function pairs generate exactly the same results?
Pair 1) names()
& colnames()
Pair 2) rownames()
& row.names()
Do the following function pairs generate exactly the same results?
Pair 1) names()
& colnames()
Pair 2) rownames()
& row.names()
As Oscar Wilde said
R is more of an evolved rather than designed language, so these things happen.
names()
andcolnames()
work on adata.frame
butnames()
does not work on a matrix:And another expansion:
If you want to assign new column names you can do following on
data.frame
:If you, however run previous command on
matrix
, you'll mess things up:Since matrix can be regarded as two-dimensional vector, you'll assign names only to first five values (you don't want to do that, do you?). In this case, you should stick with
colnames()
.So there...
Just to expand a little on Dirk's example:
It helps to think of a data frame as a list with equal length vectors. That's probably why
names
works with a data frame but not a matrix.The other useful function is
dimnames
which returns the names for every dimension. You will notice that therownames
function actually just returns the first element fromdimnames
.Regarding
rownames
androw.names
: I can't tell the difference, althoughrownames
usesdimnames
whilerow.names
was written outside of R. They both also seem to work with higher dimensional arrays:I think that using
colnames
andrownames
makes the most sense; here's why.Using
names
has several disadvantages. You have to remember that it means "column names", and it only works with data frame, so you'll need to callcolnames
whenever you use matrices. By callingcolnames
, you only have to remember one function. Finally, if you look at the code forcolnames
, you will see that it callsnames
in the case of a data frame anyway, so the output is identical.rownames
androw.names
return the same values for data frame and matrices; the only difference that I have spotted is that where there aren't any names,rownames
will print "NULL" (as doescolnames
), butrow.names
returns it invisibly. Since there isn't much to choose between the two functions,rownames
wins on the grounds of aesthetics, since it pairs more prettily withcolnames
. (Also, for the lazy programmer, you save a character of typing.)