# Basic summaries
mean(trees$DBH) # mean of tree diameters
median(trees$DBH) # median
sd(trees$DBH) # standard deviation
range(trees$DBH) # min and max
quantile(trees$DBH) # quartiles
# Basic plots
hist(trees$DBH) # histogram of diameters
boxplot(trees$DBH) # boxplot of diameters
plot(trees$DBH, trees$Mean.Growth) # scatter plot of DBH vs growthDay 2 – Describing Data
Learning goals
By the end of this day, you should be able to:
- calculate and interpret basic summary statistics (mean, median, variance, etc.)
- describe the variability and distribution of a dataset
- identify how outliers and skewness affect summary statistics
- create simple visualizations and recognize misleading plots
- understand the limitations of manual analysis for repetitive tasks
- import data into R and compute summaries and plots programmatically
- safely import/export data from R (e.g. to CSV) with correct encoding
No prior programming experience is required (we will start using R from scratch).
Motivation
After structuring data properly, the next step is to make sense of it. Large tables of numbers are hard to interpret by eye. Descriptive statistics and visualizations help us summarize key properties of the data. These summaries can reveal patterns (or problems) in our Belize biodiversity dataset, guiding further analysis. Today we learn how to compute and use these summaries, first with simple tools (like Excel) and then by transitioning to R.
Agenda
13:30–14:15 | Block 1 – Descriptive statistics fundamentals
- Recap of Day 1 data (Belize case) and need for summarizing
- Measures of central tendency (mean, median and mode) and variability (range, variance)
- Effects of outliers and skewed data on summaries
- Understanding distributions (normal vs skewed, etc.)
14:15–14:30 | Break ☕️
14:30–15:15 | Block 2 – Visualizing data effectively
- Visualizations as summaries: “a picture is worth a thousand numbers”
- Examples of honest vs misleading plots
- Best practices for clear charts (axes, labels, zero-baselines)
- Repetitive analysis tasks: Excel limitations and the need for automation
- Transition: why use R for data analysis?
15:15–15:30 | Break ☕️
15:30–16:15 | Block 3 – Hands-on: first steps in R
- Introduction to R and RStudio interface
- Importing a CSV dataset into R
- Computing summary statistics in R (e.g. mean, median, mode, SD)
- Creating a simple plot in R (histogram or boxplot)
- Exporting results (writing a CSV file)
- Discussion: comparing R workflow to Excel
16:15–16:30 | Reflection, discussion, and outlook 🧠
- Which summary or visualization was most insightful?
- How did using R compare to using Excel?
- What would you like to explore next with the data?
- Preview of Day 3: introducing programming concepts in R
From raw data to summary statistics
After data collection we end up with a raw dataset. The first question is: what do all these numbers tell us? We need to condense the data into interpretable quantities without reading every value.
Descriptive statistics are numbers that summarize certain aspects of the data. They help describe “typical” values, spread of the data, and unusual observations. Crucially, these summaries simplify the data and hide detail, so they must be used carefully.
Measures of central tendency
The mean (aka average) and median are two common measures of the “center” of a numeric dataset:
Mean (\(\bar{x}\)): the sum of all values divided by the number of values. For data points \(x_1, x_2, ..., x_n\), the mean is
\[\bar{x} = \frac{1}{n}\sum_{i=1}^{n} x_i.\]
Example: If five trees have heights (in m) 8, 10, 6, 9, 7, the mean height is \((8+10+6+9+7)/5 = 40/5 = 8\) m.Median: the middle value when data are sorted from smallest to largest. If \(n\) is odd, the median is the middle data point; if \(n\) is even, it is the average of the two middle values.
Example: For the tree heights 6, 7, 8, 9, 10 (sorted order), the median is 8 m (the third value). If we had an even number of trees, say heights 6, 7, 8, 10 (four values), the median would be the average of the two middle values (7 and 8), which is 7.5 m.
The mean and median both tell us about the “central” value of the data, but they respond differently to extreme values. The mean is influenced by outliers (very high or low values), whereas the median is more robust in skewed distributions.
- Mode: the most frequently occurring value in the dataset. This is less commonly used for continuous data but can be informative for categorical data (e.g., most common species observed).
Visualisation mode median mean

Source: Wikimedia Commons
- Open one of the regionalized files in Excel (three numeric columns A, B, C, 100 rows each):
data/raw/csv/dist_day02_sep_semicolon__dec_comma.csv(German settings: semicolon separator, comma decimal) → loads cleanly if your decimal is,data/raw/csv/dist_day02_sep_comma__dec_dot.csv(US/UK settings: comma separator, dot decimal) → if your regional decimal is,, tell Excel to keep dot as decimal One way is over Power Query import First on Home → Use First Row as Headers Delete the automatic conversion, did you notices it changed the values Select all columns clicking the first one, then shift and then the last one. Right Click → Change Type → Using Locale → Data Type [Decimal] → Locale English (Europe)
As we learned, the other way is to copy the data (from Notepad or Notebook++) and paste it into Excel. Then on Data → Text to Columns →… and at the end select Advanced There, set decimal separator to .).
- For each variable (A, B, C), calculate the mean, median and mode using Excel functions:
- Mean:
=AVERAGE(range)(German Excel:=MITTELWERT(Bereich)) - Median:
=MEDIAN(range)(German Excel:=MEDIAN(Bereich)) - Mode:
=MODE(range)(German Excel:=MODUS.EINF(Bereich); older versions:=MODUS(Bereich))
You can do this selecting a cell range with your mouse or typing it in (e.g. A2:A101 for column A) or using named ranges.
- Keep it open for later exercises.
Measures of variability
A single center value is not enough; we also need to know how spread out the data are:
Range: the difference between the maximum and minimum values. It tells us the span of the data (but can be skewed by outliers).
Outliers are extreme values that differ significantly from other observations. For example, if tree heights range from 5 m to 50 m, a tree of height 150 m can be considered an outlier.
Variance (\(s^2\)) measure the typical deviation of data points from the mean. Variance is defined as
\[s^2 = \frac{1}{n-1}\sum_{i=1}^{n} (x_i - \bar{x})^2,\]Standard Deviation (\(s\)) the square root of the variance. It is in the same units as the data and gives a sense of typical deviation from the mean. \(s = \sqrt{s^2}\). A high standard deviation means values are widely scattered around the mean; a low standard deviation means they are tightly clustered.
Note that standard deviation is the square root of variance. This changes the units:
- Variance has squared units: e.g. m(^2), mm(^2), individuals(^2)
- Standard deviation has the same units as the data: e.g. m, mm, individuals
When interpreting, standard deviation is often more intuitive because it is in the same units as the original data. Variance, however, is harderd to interpret directly bacause of squared units but is algebraically convenient and often used in statistical modeling.
Variance has clean additivity (under independence):
[ (X+Y) = (X) + (Y) X Y ]
Standard deviations do not add:
[ + ]
That is why models tend to run on variance, not SD.
- Using the same dataset (pick the same file as above)
- For each variable (A, B, C), calculate the variance and standard deviation using Excel functions:
- Variance:
=VAR.S(range)(German Excel:=VARI.S(Bereich)) - Standard Deviation:
=STDEV.S(range)(German Excel:=STABW.S(Bereich)) - Range:
=MAX(range)-MIN(range)(German Excel:=MAX(Bereich)-MIN(Bereich))
- Keep it open for later exercises.
Whay did this show you more about the data?
Percentiles/Quartiles: values that divide the data into 100 (percentiles) or 4 (quartiles) equal parts. The 25th percentile (Q1) is the value below which 25% of data fall; the 75th percentile (Q3) is the value below which 75% of data fall. Median is the 50th percentile (Q2).
Interquartile Range (IQR): the difference between the 75th percentile (Q3) and 25th percentile (Q1). This focuses on the spread of the middle 50% of data, giving a robust spread measure less affected by outliers.
For example, if the diameter at breast height (DBH) of trees in Plot A have a mean of 30 cm and a standard deviation of 5 cm, most tree DBHs are around 30 cm ± 5 cm. In Plot B, a mean of 30 cm but standard deviation of 15 cm would imply much greater variability (some saplings and some very large trees).
Both variance and SD use squared deviations, so both are sensitive to outliers.
If robustness matters, prefer: - IQR (interquartile range) - Quantiles
P.S.: robustness meaning “How strongly a statistic reacts to small violations of its assumptions, especially the presence of outliers, skewness, or heavy tails” Variance and standard deviation use squared deviations. Squaring is a megaphone. One extreme value gets amplified enormously.
Common mistakes
- Reporting variance in reader-facing summaries
- Treating mean () SD as a confidence interval (it is not)
- Comparing SDs across groups with very different distributions and pretending it is apples-to-apples
- Using SD for strongly skewed data without also reporting quantiles
The effect of outliers and skewness
Outliers (values that are very high or low relative to the rest) can heavily distort certain statistics. In ecology, suppose most trees in a sample are under 10 m tall, but one giant ceiba tree is 50 m tall. The mean tree height will be pulled upward by this one extreme value, whereas the median will barely change (since the median only cares about the middle-ranked value).
In our Belize forest data, if one plot had an anomalously high tree height count due to an observational/data entry error, the mean count would give a misleading impression of typical conditions. Always consider whether outliers are errors, natural rare events, or indications of underlying heterogeneity. Depending on context, you might report the median instead of the mean for skewed data, or even remove obvious data errors.
To gauge skewness and outliers, it’s useful to look at the whole distribution of the data, not just single summary numbers. This brings us to visualizing data.
Distributions and visual summaries
A distribution describes how frequently each value (or range of values) occurs in the dataset. Two datasets can have the same mean and variance yet be distributed very differently. Plotting the data often reveals patterns (multiple peaks, skew, outliers) that summary statistics alone might miss.
For example, consider Anscombe’s quartet – four different datasets that have the exact same mean, median, and variance, but very different arrangements of points when graphed. A visual comparison makes the differences obvious:
Four datasets with identical summary statistics (mean, variance, correlation, etc.), but very different patterns when plotted. This classic example (Anscombe 1973) shows why visualizing data is crucial: summary statistics alone can be insufficient
Source: Woodside et al 2016
The role of visualization
Graphs provide a shorthand for understanding data. By plotting our Belize dataset, we can quickly see trends and anomalies. Common plot types for quantitative data include:
- Histograms: show the distribution of a single numeric variable by grouping values into bins.
- Box plots: show median, quartiles, and outliers, giving a quick summary of distribution and spread.
- Scatter plots: show relationships between two numerical variables (e.g. tree height vs. tree diameter).
- Bar charts: summarize categorical data (e.g. mean value per category).
Data format and plotting workflows in Excel
Histogram
Distribution of a single numeric variable
- Select the numeric column (e.g.
DBH_cm) - Insert → Statistic Chart → Histogram (German Excel: Einfügen → Diagramme → Statistikdiagramm → Histogramm)
- Right-click x-axis → Format Axis
- Set bin width or number of bins
Box plot
Median, quartiles, and outliers
- Select the numeric column
- Insert → Statistic Chart → Box & Whisker (German Excel: Einfügen → Diagramme → Statistikdiagramm → Kastendiagramm (Box & Whisker))
- Excel applies Tukey’s rule automatically. Meaning: – The box spans the interquartile range (Q1 to Q3) – The whiskers extend to the most extreme values within Q1-1.5IQR and Q3+1.5IQR – Outliers are any points beyond the whiskers
- Using the same dataset (pick the same file as above that matches your regional separators/decimals)
- For each variable (A, B, C), create a histogram using Excel:
- Select the column
- Insert → Statistic Chart → Histogram (German Excel: Einfügen → Diagramme → Statistikdiagramm → Histogramm)
- Adjust bin width if needed (e.g. to 2) via right-click on x-axis → Format Axis
Much easier to see the distribution this way, right?
Relationship between two numeric variables
- Select both numeric columns
- Insert → Scatter → Scatter with only markers (German Excel: Einfügen → Punkt (X Y) → Punkte (nur Marker))
- Add axis labels and optional trendline
- Open a new Excel instance
- Load the Belize dataset
data/raw/PSP/PSP_NPD847_OH.xlsxBefore plotting, think, how should a scatter plot of DBH vs Height look like? What relationship do you expect? - Select the columns
DBHandHeight - Insert → Scatter → Scatter with only markers
Bonus 1. Make this plot at the Analysis sheet (not raw data) 2. Add a trendline via right-click on a point → Add Trendline… 3. Choose Linear and logarithmic options 4. Add equation and R-squared value to the chart
R-squared (R²) is a statistical measure of how well a regression model fits your data. It answers the question: “How much of the variation in the outcome (Y) can be explained by the predictor(s) (X)?” If 0 model explains none of the variation, if 1.0 it explains all the variation (perfect fit) Note A high R² does not mean the model is good… in biology, natural variation is high. R² ignores bias and overfitting. Use diagnostics and validation too.
What is the relationship between DBH and Height in this dataset? Does it match your expectation?
A good visualization summarizes the data (like statistics do) but in a more intuitive way. It is not “proof” of a hypothesis by itself, but it helps us explore and communicate what the data are saying.
Honest versus misleading plots
Not all charts are created equal. It’s easy to mislead with visuals, intentionally or not. One common pitfall is manipulating the axes to exaggerate or downplay differences or showing only a narrow range on the y-axis can make a tiny difference look huge.
Misleading Data Visualizations: From mistakes to fraud, bad graphs can distort the truth.

Source: Ana Kin 2023 - Medium
When creating plots, follow these best practices: - Start axes at zero for bar charts (so heights are proportional to values). Only truncate axes if necessary for clarity, and clearly indicate breaks if used. - Label axes and units clearly. A viewer should know what the x and y values represent. - Avoid “chart junk” – unnecessary 3D effects, excessive colors, or anything that distracts from the data. - Use appropriate plot types: e.g. don’t use a pie chart if you have many categories (it becomes hard to read). - Be honest with visual encodings: for example, if doubling area in a pictogram, ensure area truly corresponds to value (our brains interpret area non-linearly, so this can mislead).
In Excel, creating a basic chart (Insert → Chart) is straightforward, but be cautious: Excel might auto-format charts in ways that aren’t ideal (e.g., truncated axes or confusing legends). Always review and tweak the default settings to ensure clarity and honesty.
Beware of accidental distortion: Even well-meaning choices, like using a logarithmic scale or excluding outliers for clarity, can confuse or mislead if not communicated. Always caption or annotate your plots to make such choices clear.
Group exercise: Visualize data in Excel (10 minutes)
Using the Belize and Amazon dataset create: - One histogram - One box plot - One scatter plot - One bar chart (using a PivotTable)
When Excel falls short: repetition and scalability
If you have a small dataset, you can calculate means or make a plot in Excel by hand without much trouble. But what if you have dozens of variables or need to repeat the same calculation for multiple groups? This is where Excel becomes tedious and error-prone, and why we turn to R.
Imagine you have species count data for 50 different areas and you want the average count for each species in each area. In Excel, you might set up a complex grid of formulas or create 50 separate pivot tables – a process that is both time-consuming and fragile (any new data or slight change, and you must update everything manually). In R, you could compute all those summaries with a few lines of code that can be reused anytime the data updates.
Reproducibility: Another limitation of point-and-click analysis is that it’s hard to retrace or repeat exactly. If someone asks “How did you get this number?”, you might have to recall a sequence of steps you did in Excel. In R, every step is scripted, so you (and others) can always check the code to see how a result was obtained and rerun it on new data.
Accuracy: Manual work is prone to mistakes (copy-paste errors, wrong cell ranges, etc.). By writing an explicit script, you reduce the risk of such errors, especially when tasks are repetitive.
Excel does have tools like PivotTables and formulas that can automate some analyses. PivotTables, for example, allow quick grouping and summarizing of data by categories (e.g. mean count per species per site). We used some Excel features on Day 1 to structure data. However, for complex or repetitive tasks, maintaining many pivots and formulas can become a nightmare of cross-references and as we saw, error susceptible. R, by contrast, is great at handling repetition: you can loop through all species or use vectorized operations to compute results for all groups in one go.
In summary, Excel is often the easiest for one-off calculations or small tasks, but R is better for automating analyses, handling larger datasets, and ensuring reproducibility. Next, we’ll get hands-on with R and perform some of the same summaries and plots we did in Excel – but faster and in a way that scales up.
First steps in R
R is a programming language and environment specifically designed for data analysis and statistics. We will use R through RStudio, a user-friendly interface.
To follow along:
Open RStudio. You’ll see the Console in one pane and possibly an empty script editor in another. You can type R commands directly into the Console, or write a script in the editor pane and run it.
Create a new R script: Go to File → New File → R Script. This allows you to save a record of your commands (which is great for reproducibility).
Importing a dataset into R
We will start by importing a CSV file of data (for example, the tree measurement dataset we structured on Day 1). In Excel, we opened this file by double-clicking or via Data → Import. In R, we use a function call.
Assuming the CSV file is saved as data/raw/trees.csv (just as an example path), we can read it into R with:
# Read the CSV file into a data frame (tabular structure in R)
trees <- read.csv("data/raw/csv/Caxiuana_tree_trait_data.csv")This command loads the data into a variable named trees. By default, read.csv assumes the file has a header row for column names, values are separated by commas, and text is encoded in UTF-8 (which is standard for most CSVs). If our data used a different delimiter (like tab \t in a TSV file), we could use read.delim or specify sep=“\t”. One big advantage: R will not automatically mangle our data the way Excel might. For instance, if there were gene names like “SEP2” or “MAR1”, R will keep them as text, whereas Excel might have turned them into dates or numbers. In R, data types are explicit – we can tell R a column is text, numeric, etc., or let it guess (which it usually does correctly if the file is well-formatted).
Tip: If your data contains special characters (like “ß” or “ñ”), ensure you use the correct encoding. read.csv(…, fileEncoding=“UTF-8”) will handle most cases. This prevents issues where characters turn into gibberish due to encoding mismatches.
Summarizing data in R
Now that our data is in R as a data frame (trees in the example), we can compute the same summary statistics as before:
The functions mean(), median(), sd() (standard deviation), range() and others do the math for us. By default, these will return NA (Not Available) if any missing values are in the data. To ignore missing values (NA) in calculations, we add an argument like na.rm=TRUE (e.g., mean(trees$dbh_cm, na.rm=TRUE)). For a quick overview of an entire data frame, R has the handy summary() function.
# mean of vector with NA
vect <- trees$Mean.Growth
mean(vect)
mean(vect, na.rm=TRUE) # ignore NAs
# Summary of all columns
summary(trees)summary(trees) outputs, for each column, some summary info (for numeric columns: min, Q1, median, mean, Q3, max; for factors or characters: a preview of values or counts). It’s an instant way to see the shape of your data. If we have categorical variables (e.g. species or site name), we might want to see counts or group-wise summaries. In R, it’s easy to do by grouping the data. For instance, to get the mean dbh_cm per species:
# mean DBH per species
meanDBH <- aggregate(DBH ~ Species, data = trees, FUN = mean)
# report number of observations per species
count <- aggregate(DBH ~ Species, data = trees, FUN = length)
# merge summaries
summary_table <- merge(meanDBH, count, by="Species")
colnames(summary_table) <- c("Species", "Mean_DBH", "Count")
# exclude species with less than 5 observations
subset_summary_table <- subset(summary_table, Count >= 5)
#or alternatively
subset_summary_table <- summary_table[summary_table$Count >= 5, ]
# or alternatively using dplyr package
install.packages("dplyr") # run this line once to install dplyr
library(dplyr)
subset_summary_table <- filter(summary_table, Count >= 5)
# or alternatively
subset_summary_table <- summary_table |> filter(Count >= 5)This single line replaces what might be a complex PivotTable in Excel, giving us a table of mean diameters for each species in our dataset. We’ll explore more powerful grouping and summarizing (with the dplyr package) on later days, but this shows the idea.
Work in pairs (one “driver” at the keyboard, one “navigator” guiding):
- Load the dataset
csv/Caxiuana_tree_trait_data.csvinto R.
Alternatively, load the Excel file Foresty/PLOT_Data_2020/PLOT_2016.10_2020.xlsx into R. For this, you will need a package, i.e. openxls to load a .xlsx file, specifically the read.xlsx() function.
install.packages("openxlsx") # run this line once to install openxlsx
library(openxlsx)
fplot <- read.xlsx("./data/raw/Foresty/PLOT_Data_2020/PLOT_2016.10_2020.xlsx",sheet=1, startRow=9)[-1,]Try to figure out what this is doing!
Using R, calculate the mean and median of a key variable across all observations.
Create a histogram and a boxplot.
Discuss with your partner: Do the mean and median differ notably? What does that tell you about the distribution (skewness or outliers)? Did you intuition matched what you saw on the histogram?
Switch roles (driver/navigator) halfway through. This exercise gives you first-hand experience with R’s commands. Don’t worry if you get stuck – use ?functionName (e.g. ?mean) to access R’s help, or ask an instructor for a hint. Soon we will dive deeper
Exporting data and results
Just as important as reading data into R is writing it out. If you cleaned or summarized data in R, you might want to save it as a CSV to share or to use in a report:
write.csv(trees, "data/clean/trees_clean.csv", row.names = FALSE)This would save our trees data frame to a new CSV file (without including row numbers as an extra column). By default, write.csv writes in UTF-8 encoding on most systems, which will preserve special characters. R can also save plots to files (PNG, PDF, etc.). Another powerful approach is to use R Markdown or Quarto (as we are doing for these course materials) to integrate text, code, and plots in one reproducible document. We will delve into that on Day 4. For now, the key point is: with a few lines of code, we imported data, computed summaries, made plots, and saved outputs. Once written, we can reuse this code anytime with new data, ensuring consistent analysis. This is a taste of what’s possible as we move further into R.
Wrap-up
Today we learned how to describe and visualize data, transitioning from manual Excel steps to automated R scripts. Descriptive statistics like mean, median, and standard deviation condense data into understandable numbers, while visualizations reveal patterns and anomalies that numbers alone might hide. We also saw the first glimpses of R’s capabilities – from reading data to making a plot in seconds. By summarizing the Belize case study data, we gained insight into typical values and variability (e.g., average tree sizes, distribution of observations across sites). We also confronted how misleading it can be if we rely on a single number or a poorly crafted chart. In the next session, we’ll build on this foundation by asking: How can we automate analyses and go beyond what spreadsheets allow? This will lead us deeper into the world of programming (using R) – writing instructions to let the computer handle repetitive tasks and complex logic, which is our focus for Day 3. Feel free to practice more with R on your own: try computing stats or making charts for other variables in the dataset. The more you play with the data, the more familiar you will become with R.
If you switch between regions: both CSV variants of dist_day02 load cleanly when the separator and decimal match your settings. In R, set sep and dec explicitly (see below) and both files produce the same numeric results. In Excel, either pick the semicolon/comma file when your decimal is ,, or if you open the comma/dot file under a comma-decimal locale, use Power Query or Data → Text to Columns → Advanced and set decimal separator to . so numbers are parsed correctly.
install.packages("here") # run this line once to install here
library(here)
# Read CSV with different separators/decimals; both give identical data when sep/dec match
tab <- read.csv(here("./data/raw/csv/dist_day02_sep_comma__dec_dot.csv"), sep=",", dec=".")
# you can also load the other variant:
# tab <- read.csv(here("./data/raw/csv/dist_day02_sep_semicolon__dec_comma.csv"), sep=";", dec=",")
str(tab)
hist(tab$A)
hist(tab$B)
hist(tab$C)- Which statistic or visualization surprised you?
- How was your first experience using R? What was challenging, and what felt easier or more powerful than using Excel?
- What would you like to explore next with R or data analysis? If you can, please take a moment to provide feedback on today’s session:
- Anonymous feedback