[R] Column renaming

Peter Dalgaard P.Dalgaard at biostat.ku.dk
Mon May 5 17:19:43 CEST 2008


Chip Barnaby wrote:
> Dear all,
>
> Is there a less cumbersome way to rename a column by name (as opposed
> to index) than --
>
> names( X)[ names[ X] == "bob"]<-"sue"
>
> ?
Not that I know of (notwithstanding that your code doesn't quite work as
it stands...). You might have thought that this would work, but it
obviously does not:

> names(airquality["Ozone"]) <- "O3"
> head(airquality)
  Ozone Solar.R Wind Temp Month Day
1    41     190  7.4   67     5   1
2    36     118  8.0   72     5   2
3    12     149 12.6   74     5   3
4    18     313 11.5   62     5   4
5    NA      NA 14.3   56     5   5
6    28      NA 14.9   66     5   6

(This is probably a design decision. In the same vein,

airquality[6] <- data.frame(foo=1:153)

will not change the name of column 6. It might be preferable if it did,
from the conceptual point of view, but it is one of those things where I
suspect that the world comes tumbling down if you try to change the
behaviour...)

>
> A semi-related question: how does one get the index of a column by
> name, something along the lines of col.index( X, "sue") ?
>
match("sue", names(X))

-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark      Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)              FAX: (+45) 35327907



More information about the R-help mailing list