Is it possible to swap columns around in a data frame using R?

baz picture baz · Apr 20, 2011 · Viewed 56k times · Source

I have three variables in a data frame and would like to swap the 4 columns around from

"dam"   "piglet"   "fdate"   "ssire"

to

"piglet"   "ssire"   "dam"   "tdate"

Is there any way I can do the swapping using R?

Any help would be very much appreciated.

Baz

Answer

IRTFM picture IRTFM · Apr 20, 2011
dfrm <- dfrm[c("piglet", "ssire", "dam", "tdate")]

OR:

dfrm <- dfrm[ , c("piglet", "ssire", "dam", "tdate")]