# A comment starts with #
print("Hello, R!")[1] "Hello, R!"
Oskar Hagen
This is an R Tutorial. We will learn the basics with tree measurements like height and DBH (diameter at breast height).
Run code blocks in RStudio or directly in R terminal. Lines that start with # are comments.
Imagine you measured a tree height in meters.
In R, <- is the classic assignment arrow. You can also use = but <- is more common.
dbh_cm with a DBH value (in centimeters).plot_id with a number.dbh_cm and print the result.Vectors are lists of values of the same type.
heights_m with 5 tree heights.Data frames are tables. Each column can be a different type.
Functions like data.frame() expect “(” and “)” to enclose arguments. If you opoen a parenthesis, R expects you to close it. That’s why you see the + sign in the console until you close it.
Functions let you reuse code.
m_to_cm that takes a numeric input in meters and returns the value in centimeters. use ‘function()’ to define the function and remember that 1 meter = 100 centimeters.height_m in the trees data frame to centimeters using your function and add it as a new column height_cm. use ‘$’ to add the new column to the data frame.Try changing colors with col = "forestgreen" or pch = 19.
A tiny calculation you might do in the field is basal area. Here is a very simple version using DBH in centimeters.
tree_id and height_cm (4 rows). use ‘data.frame()’ to create the data frame.dbh_cm. use ‘$’ to add the new column. You can also use ‘cbind()’ to combine the data frame and vector.sample() to pick 2 random trees from trees$tree_id.If you get stuck, run code line by line and use ‘?’ to get help, e.g., ?median.
install.packages("here")
library(here)
urls <- list("https://raw.githubusercontent.com/ohagen/course_DigitalCompetenceInTheBiologicalSciences/refs/heads/main/data/raw/PSP/PSP_NPD42_OH.csv",
"https://raw.githubusercontent.com/ohagen/course_DigitalCompetenceInTheBiologicalSciences/refs/heads/main/data/raw/PSP/PSP_NPD847_OH.csv")
dest <- list("PSP_NPD42_OH.csv",
"PSP_NPD847_OH.csv")
for (i in 1:length(urls)) {
download.file(urls[[i]], dest[[i]], mode = "wb")
}
#list files ending in cvs in working directory
csvs <- list.files(path = here("./data/raw/PSP/"), pattern = "\\.csv$", full.names = TRUE)
# load each csv and merge into a single data frame
all_data <- do.call(rbind, lapply(csvs, read.csv))
# the same as above but more explicit using loops
all_data <- data.frame()
for (file in csvs) {
#get file name from file
f_name <- basename(file)
# remove .csv at the end and PSP_
f_name <- gsub("^PSP_|\\.csv$", "", f_name)
print(f_name)
# read csv
temp_data <- read.csv(file)
# add new column with file name
temp_data$PSP <- f_name
print(dim(temp_data))
all_data <- rbind(all_data, temp_data)
}
dim(all_data)
str(all_data)
# spot values that can not be converted to numeric in DBH or Height
mask <- is.na(as.numeric(all_data$DBH))
all_data[mask,]
# manual fix of DBH
# there was text instead of number for Tag.Number 1234 in PSP NPD42_OH on DBH. i.e. 1o.4
all_data[all_data$Tag.Number==1234&all_data$PSP=="NPD42_OH", "DBH"] <- 10.4
# convert DBH to numeric
all_data$Height <- as.numeric(all_data$Height)
# plot scatterplot dbh vs height for each PSP
plot(all_data$DBH, all_data$Height,
main = "Tree Height vs DBH",
xlab = "DBH (cm)", ylab = "Height (m)", col = as.factor(all_data$PSP))
# add legend for PSP
legend("topleft", legend = unique(all_data$PSP), col = 1:length(unique(all_data$PSP)), pch = 1)Identify trees with height smaller than 200 cm. Use logical indexing to filter rows where height > 100. (e.g. all_data[all_data$Height<200,])
Remove the outlines from the data frame, you talked with people that collected the data first! ;) Use logical indexing to keep only rows where height >= 100, or remove rows with height < 100. you can either use the function ‘which’, or use logical indexing directly. Remember ‘!’ means NOT in R, thus a vector x <- c(F, T, F), then !x is c(T, F, T)
Remove any tree that is deadwood from the data frame. Use logical indexing to keep only rows where Deadwood column is FALSE.
# remove any entry with Species containing "Dead wood"
data_no_DeadWood <- all_data[!grepl("Dead wood", all_data$Species), ]
# alternatively, remove any entry on Species containing "Dead wood (CLASS 1)" or "Dead wood (CLASS 2)" using %in%
data_no_DeadWood <- all_data[!(all_data$Species %in% c("Dead wood (CLASS 1)", "Dead wood (CLASS 2)")), ]Hint: remove the ‘!’ to check the selection before you remove. Also use ‘dim()’ to check the size of the data frame before and after removing rows.
In order to keep your workflow clean, it is recomended that intermediate results are saved to files. This way you can always go back to a previous step without re-running everything.
Also, save the scripts in separate steps, e.g. 01_load_data.R, 02_clean_data.R, 03_analyze_data.R, etc.