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é
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
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
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With