[R] Maintaining specific order when using aggregate or change order on axis

Rui Barradas ruipbarradas at sapo.pt
Tue Sep 11 20:37:25 CEST 2012


Hello,

If you order your original (wanted) order and then order that result you 
get what you want.
The example is with fake data but the idea is in the last two lines.


# Make up some data
set.seed(9210)
n <- 1e2
depth <- c('surface', 'shallow', 'deep', 'fmax', 'below')
dat <- data.frame(Depth = sample(depth, n, TRUE), Value = runif(n))

# This is sorted by increasing Depth
agg <- aggregate(Value ~ Depth, data = dat, FUN = mean)

ix <- order(depth)  # First step
agg[order(ix), ]  # inverse permutation

Hope this helps,

Rui Barradas

Em 11-09-2012 18:52, Tinus Sonnekus escreveu:
> Hi All,
>
> I'm using the following code to produce some stacked bar graphs.
>
> *setwd("C:\\Users\\Tinus\\Documents\\NMMU\\R\\Seamounts")*
> *SChla <- read.csv("SM_Chla_data.csv")*
> *
> *
> *#Extract mean values from data file*
> *
> *
> *Coral <- SChla[185:223,] #Reduce SChla to Coral only*
> *coral <- with(Coral , aggregate(cbind(Pico, Nano, Micro),
> list(Depth),FUN=mean))*
> *rownames(coral) <- coral[,1] *
> *coral <- t(coral[,-1]) # Remove Station col and transpose*
>
> *barplot(coral, main="Size fractionated Chl a for Coral", *
> * ylab = "Coral", xlim = c(0,8), horiz = TRUE,*
> * xlab = expression ("Chlorophyll a " ~~ (mu*g ~ l^{-1})), *
> * col =c("light green", "green", "dark green"),*
> * legend = rownames(coral))*
>
> Here is the *head(Coral) *before station col removal and t()
>      Seamount Station   Depth  Pico  Nano Micro Total_Ch
> 185    Coral    1401 Surface 0.216 3.270 4.240    7.726
> 186    Coral    1401    Fmax 0.359 3.890 4.900    9.149
> 187    Coral    1401   Below 0.178 1.360 1.210    2.748
> 188    Coral    1402 Surface 0.231 4.140 3.670    8.041
> 189    Coral    1402    Fmax 0.863 4.340 3.750    8.953
> 190    Coral    1402   Below 0.176 0.386 0.214    0.776
>
> So I use the same code for the six other seamounts. The depth has
> the following values  surface, shallow, deep, fmax and below . These are in
> order as you go down the water column. The problem is when I use the *coral
> <- with(Coral , aggregate(cbind(Pico, Nano, Micro), list(Depth),FUN=mean)) *the
> depth values gets stored in ascending values.
>
> head(coral)
>    Group.1      Pico      Nano     Micro
> 1   Below 0.1652727 0.8610909 0.7227273
> 2    Deep 0.1480000 1.1700000 1.1000000
> 3    Fmax 0.3067273 3.1845455 3.2245455
> 4 Shallow 0.2617500 1.8242500 1.8637500
> 5 Surface 0.1693333 2.7083333 2.7858333
>
> I would like to maintain the order surface, shallow, deep, fmax and below. *Or
> *if there is a way I can rearrange the yaxis in the order surface, shallow,
> deep, fmax and below.
>
> Any suggestions?
>
> Thank you
> Tinus
>




More information about the R-help mailing list