[R] Reorder data frame columns by negating list of names

From: Thompson, David (MNR) <David.John.Thompson_at_ontario.ca>
Date: Tue, 12 Feb 2008 12:19:43 -0500


Hello,

I would like to reorder columns in a data frame by their names as demonstrated below:

Take this data frame:

> xxx <- data.frame(matrix(1:40, ncol=8))
> names(xxx) <- letters[1:8]
> xxx

	  a  b  c  d  e  f  g  h
	1 1  6 11 16 21 26 31 36
	2 2  7 12 17 22 27 32 37
	3 3  8 13 18 23 28 33 38
	4 4  9 14 19 24 29 34 39
	5 5 10 15 20 25 30 35 40

and reorder the columns like this:

> xxx[,c( c('b', 'd', 'h'), c('a', 'c', 'e', 'f', 'g') )]
b d h a c e f g 1 6 16 36 1 11 21 26 31 2 7 17 37 2 12 22 27 32 3 8 18 38 3 13 23 28 33 4 9 19 39 4 14 24 29 34 5 10 20 40 5 15 25 30 35

where I only have to name the columns that I'm interested in moving to the first few positions, something like:

> xxx[,c( c('b', 'd', 'h'), -c('b', 'd', 'h') )]
        Error in -c("b", "d", "h") : invalid argument to unary operator

Suggestions? and Thank you, DaveT.



Silviculture Data Analyst
Ontario Forest Research Institute
Ontario Ministry of Natural Resources
david.john.thompson_at_ontario.ca
http://ofri.mnr.gov.on.ca

R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Tue 12 Feb 2008 - 17:31:48 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 12 Feb 2008 - 19:30:14 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive