Doro - 3 months ago 17

R Question

I want to show boxplots with *mean* values in ** R**. My boxplots are representing catalase activity on 6 different sites, which I want to reorder from North to South with an Referent site at the end (N1,N2,M1,M2,S1,S2,R). I can easily reorder boxplots like this:

`levels(data$site)`

[1] "S2" "N1" "R" "N2" "S1" "M1" "M2"

x = factor(data$site,levels(data$site)[c(2,4,6,7,5,1,3)])

boxplot(catalase~x, data)

But

I'm calling mean values like this:

`means<-tapply(data$catalase, data$site, mean)`

points(means, col="red", pch=19)

And tried reorder them like this:

`reordered_means = factor(means,levels(means)[c(2,4,6,7,5,1,3)])`

But obviously that doesn't make sence, since it's not working.

Suggestions, please?

Answer

What you need is not

```
reordered_means = factor(means,levels(means)[c(2,4,6,7,5,1,3)])
```

but

```
reordered_means = means[c(2,4,6,7,5,1,3)]
```

**Example**

```
## toy data: z ~ site
site <- gl(7 , 5, labels = c("S2", "N1", "R", "N2", "S1", "M1", "M2"))
set.seed(0); z <- round(rnorm(35), 2)
## re-level
piv <- c(2,4,6,7,5,1,3) ## pivoting index
x <- factor(site, levels(site)[piv])
## old mean before re-levelling
means <- tapply(z, site, mean)
## new mean after re-levelling
reordered_means <- means[piv]
# N1 N2 M1 M2 S1 S2 R
#-0.074 -0.370 -0.066 -0.226 0.206 0.788 -0.356
## we can verify this by computing from scratch
reordered_means <- tapply(z, x, mean)
# N1 N2 M1 M2 S1 S2 R
#-0.074 -0.370 -0.066 -0.226 0.206 0.788 -0.356
```