Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

swap

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

like image 977
baz Avatar asked Apr 20 '11 00:04

baz


People also ask

How do I swap columns and rows in R?

Thus, to convert columns of an R data frame into rows we can use transpose function t. For example, if we have a data frame df with five columns and five rows then we can convert the columns of the df into rows by using as. data. frame(t(df)).

How do you flip a Dataframe in R?

To interchange rows with columns, you can use the t() function. For example, if you have the matrix (or dataframe) mat you can transpose it by typing t(mat) . This will, as previously hinted, result in a new matrix that is obtained by exchanging the rows and columns.


1 Answers

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

OR:

dfrm <- dfrm[ , c("piglet", "ssire", "dam", "tdate")] 
like image 114
IRTFM Avatar answered Sep 20 '22 20:09

IRTFM