[R] Extract a 'data.frame$column' column name

(Ted Harding) Ted.Harding at manchester.ac.uk
Mon May 3 13:36:39 CEST 2010

On 03-May-10 11:09:43, adrien Penac wrote:
> Hello,
>   I can't find how to get de column name from a data.frame dollar
> reference.
> To make it simple, I'd like to obtain "Bar" from a "foo$Bar" notation.
> I've tried col.names(foo$Bar), names(foo$Bar) and so on without sucess.
> Regards
> Blaise

You cannot expect to! The reason is that foo$Bar is the object
which is stored in list/dataframe foo *under* the name "Bar".
"Bar" is the index, within foo, of that object.

That object may be something that has a "names" attribute
(such as a matrix with column names), and this it what would
be returned by anything like names(foo$Bar); there is no reason
to expect that such names should have any relationship with "Bar".

However, I have to ask why you want to find the solution to such
a question.

In any code which has already extracted foo$Bar from foo, that
code has done so by constructing the expression "foo$Bar", and
so the code already knows the value "Bar" -- so look for it
in the code!

A possible exception to that secario is where you want to find
out the name of a list/dataframe component in a particular
position -- for example, you may want the name under which
the 3rd compenent is indexed. For example:

  # [1] "Bar1" "Bar2" "Bar3" "Bar4"

  # [1] "Bar3"

Hoping this helps; if not, then more information is needed
about why you are asking the question!


E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 03-May-10                                       Time: 12:36:35
------------------------------ XFMail ------------------------------

More information about the R-help mailing list