[R] Re order variables in a dataframe

Peter Dalgaard p.dalgaard at biostat.ku.dk
Thu May 21 10:45:43 CEST 2009


Simon Blomberg wrote:
> How about to insert a variable a2 inbetween the first and second columns
> of dat:
> 
>  dat2 <- cbind(dat[,1], a2=a2, dat[,2:3])
> 
> Where a2 is the new variable. This mangles the variable name for column
> 1, unfortunately. Surely someone else will offer a better solution.
> 
> Simon.

Just lose the commas:

 > head(cbind(aq[1],data.frame(log(aq$Ozone)),aq[2:6]))
   Ozone log.aq.Ozone. Solar.R Wind Temp Month Day
1    41      3.713572     190  7.4   67     5   1
2    36      3.583519     118  8.0   72     5   2
3    12      2.484907     149 12.6   74     5   3
4    18      2.890372     313 11.5   62     5   4
5    NA            NA      NA 14.3   56     5   5
6    28      3.332205      NA 14.9   66     5   6

(Otherwise the infamous drop-to-vector effect will bite you and you need 
drop=FALSE, but this does not apply to list-like indexing. For matrices 
you do need drop=FALSE.)

-- 
    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