# Some R codes

Here are some of the R codes and packages I have been using in my research. These are simplified summaries to help you start applying them to your own data.  Let me know if you would like more explanations of their usage and interpretation.

If you don’t have R installed yet, go to http://www.r-project.org, and then download also RStudio for easier visualisation and organisation of your R scripts and data.

Calculate Functional Diversity:

Functional Distance (as in Walker et al. 1999, Ecosystems):

```# Calculate the functional distance between every two species,
# where species are characterized by a set of traits

fDist <- dist(traits, "euclidean")
```

Functional Dipsersion (as in Laliberté & Legendre 2010, Ecology)

```# Calculate a measure of functional dominance ("functional dispersion")
# for each sample unit composed of an abundance matrix and a trait matrix
# that characterizes the species
library(FD)
fDisp <- dbFD(traits, abundance)

# Access the results of Functional Dispersion
fDisp\$FDis

# Access the Community-Weighted Mean trait values (CWM)
fDisp\$CWM
```

Statistical analyses:

Structural Equation Modelling

```library(laavan)
model<-'
response ~ predictor1 + predictor2 + predictor3
predictor1 ~ predictor2 + predictor3
'

fit <- sem(model, data = data)

summary(fit, fit.measures=TRUE, rsquare=TRUE)

# Remeber to check out residuals and unexplained covariances:
residuals(fit)
inspect(fit, "cov.lv")

library(piecewiseSEM) # for SEM using Mixed Effect Models
```

Mixed Effect Models

library(nlme)
model1 <- lme(response ~ predictor1 * predictor2, random =~ 1|random,
correlation = yourCorrelationStructure, data)