[R] Swap variables in data.frame

Rogers, James A [PGRD Groton] James.A.Rogers at pfizer.com
Tue Jun 3 14:05:37 CEST 2008


Birgit Lemcke wrote:

> I have a dataframe and two of my variables are in the wrong position 
> and I would like to swap those variables. 

In addition to the other solutions posted, if you prefer to reference
the columns by name rather than by index, you could use subset() 

dat <- data.frame(a = letters[1:3], b = LETTERS[1:3], c = 1:3, d = 3:1)

subset(dat, select = c(b, a, c, d))
## or equivalently, something like:
subset(dat, select = c(b:a, c:d))


--Jim 

James A. Rogers, Ph.D. 
Associate Director, Neuroscience Statistics
Pfizer Global R&D New London
50 Pequot Avenue (MS 6025-B2131)
New London, CT 06320
office: (860) 732-0783
cell: (860) 501-7228
fax: (860) 686-7866

 



More information about the R-help mailing list