Skip to content

about sorting table

4 messages · Uwe Ligges, Martin Maechler, Mike Prager

#
herodote at oreka.com wrote:

            
see ?colnames

Uwe Ligges
#

        
UweL> herodote at oreka.com wrote:
>> hi all,
    >> 
    >> I load a table with headers that enable me to acces it by the column names:
    >> 
    >> tab<-read.table("blob/data.dat",h=T)
    >> attach(tab)
    >> 
    >> everythings are OK, but i try to sort this table against one of his column like this:
    >> 
    >> tab<-tab[order(tab$IndexUI),];
    >> 
    >> It is still ok, the table is sorted, if i type "tab" i see a sorted table.
    >> 
    >> but, when i call the column by their names, it appears that the column isn't sorted...
    >> 
    >> I believe that, is there a solution to attach column names another time, to reflect the effect of sorting this table?
    >> 
    >> thks all for your answers

    UweL> see ?colnames

eehm, that won't really help here.

The problem is that Guillaume
- first attach()ed the data frame
- then changed the data frame itself,
- and then erronously assumed that the *attached* data would change.

In general, we nowadays recommend quite often against using attach()
but rather use the 'data = ' argument where applicable and use
with( <data frame> , <......> ) 
otherwise.

Martin Maechler, ETH Zurich
#
Martin Maechler wrote:

            
Ah, thank you, MArtin, I overlooked that line ....

Uwe
#
on 12/1/2005 4:05 AM Martin Maechler said the following:
Yes, may I add this for Guillaume?  I like to think that "attach()" 
makes a *read-only* copy of the data frame's columns.  That may not be 
exactly what R does, but as a metaphor, it provides a way to think about 
what happens.

You can get what you wanted by

attach(tab)
... sorting code...
detach()
attach(tab)

but as Martin says, it is nicer to use 'with()' rather than 'attach()', 
and many functions do take a 'data=' argument.  (I hope that 'data=' 
will spread quickly to more R functions.)

If you search the archives, you will find a very nice function, 
'sort.data.frame()', by Kevin Wright.  It allows sorting by several 
columns and in ascending and descending order without writing the basic 
code each time.

MHP