Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reordering rows in a data.frame?

Tags:

r

All I need is to swap every two rows in this table... Basically swap every row containing 'chao1' with the next row, which certainly contains 'obs'.

All the examples I have come accross seem to have a previous reference for that, but what I am looking for, I think, is a bit different.

     Group.1                  var     S           se    
1    Cliona celata complex    chao1   800.5933    57.51779
2    Cliona celata complex    obs     495.4286    63.07360
3    Cliona viridis           chao1   432.5548    35.87778
4    Cliona viridis           obs     286.0000    55.32179
5    Dysidea fragilis         chao1   694.9129    74.85536
6    Dysidea fragilis         obs     357.6667    64.02170
7    Phorbas fictitius        chao1   851.6950    57.67145
8    Phorbas fictitius        obs     523.2500    23.57905

Thank you in advance for all the help!

Cheers,

André

like image 488
André Soares Avatar asked Jun 03 '15 21:06

André Soares


3 Answers

A quick way of doing this is using data.table devel version setorder which will reorder your data set in place too

#### To install development version
## library(devtools)
## install_github("Rdatatable/data.table", build_vignettes = FALSE)

library(data.table) # V >= 1.9.5
setorder(df, Group.1, -var)
#                 Group.1   var        S       se
# 2 Cliona celata complex   obs 495.4286 63.07360
# 1 Cliona celata complex chao1 800.5933 57.51779
# 4        Cliona viridis   obs 286.0000 55.32179
# 3        Cliona viridis chao1 432.5548 35.87778
# 6      Dysidea fragilis   obs 357.6667 64.02170
# 5      Dysidea fragilis chao1 694.9129 74.85536
# 8     Phorbas fictitius   obs 523.2500 23.57905
# 7     Phorbas fictitius chao1 851.6950 57.67145
like image 167
David Arenburg Avatar answered Oct 04 '22 02:10

David Arenburg


Here is something that works using a trick that David taught me just a few hours ago :). It also requires an even number of rows and them being ordered properly.

 df <- data.frame(g1=c("a","a","b","b"),var=c(1,2,3,4))
 df
 #   g1 var
 # 1  a   1
 # 2  a   2
 # 3  b   3
 # 4  b   4

 n <- nrow(df)
 sidx <- trunc(seq(0,n-1)/2)*2 + rep(c(1,0),n/2) + 1
 df <- df[sidx,]
 df

 #   g1 var
 # 2  a   2
 # 1  a   1
 # 4  b   4
 # 3  b   3
like image 36
Mike Wise Avatar answered Oct 04 '22 03:10

Mike Wise


Assuming your data frame has an even number of rows you can do this:

n <- nrow(df)
x <- matrix(1:n, ncol=2, byrow=TRUE)
y <- x[,2:1]
inds <- as.numeric(t(y))
new.df <- df[inds,,drop=FALSE]
like image 23
Bridgeburners Avatar answered Oct 04 '22 03:10

Bridgeburners