# Bopbun R course chapter 4. Bob, 2026-11-28. CC0-1.0.
# Original simulated input. Run in the folder containing data.csv.

seedlings <- read.csv("data.csv", na.strings = c("", "NA"))  # Read the table, treating blank cells and NA text as missing entries.
print(seedlings)  # Display the original six-row table.
nrow(seedlings)  # Count the six seedling rows.
ncol(seedlings)  # Count the two columns: name and height.

missing <- is.na(seedlings$height_cm)  # Mark the height entries that are missing.
missing  # Show six yes/no answers in the original seedling order.
sum(missing)  # Count the missing entries; the result is 1.
seedlings$seedling[missing]  # Show C, the name at the missing position.

mean(seedlings$height_cm)  # Keep the missing entry in the calculation and observe NA.
mean(seedlings$height_cm, na.rm = TRUE)  # Average the five recorded heights: 63 divided by 5 is 12.6 cm.
sum(seedlings$height_cm, na.rm = TRUE)  # Add the five recorded heights to obtain 63 cm.
sum(!missing)  # Reverse the missing marks and count five recorded entries.

observed <- seedlings[!missing, ]  # Keep the recorded rows and both columns in observed.
print(observed)  # Display the five rows A, B, D, E and F.
barplot(observed$height_cm,  # Use the five recorded heights as bar lengths.
        names.arg = observed$seedling,  # Place each seedling name beneath its bar.
        col = "#0066CC", border = NA, ylim = c(0, 20),  # Use blue bars without outlines and a vertical range of 0 to 20 cm.
        xlab = "Seedling", ylab = "Height (cm)",  # Label the horizontal axis with seedlings and the vertical axis in cm.
        main = "Five recorded heights")  # Give the chart a title describing the five recorded values.

practice <- seedlings  # Start the exercise from a copy of the original six-row table.
practice[3, "height_cm"] <- 9  # Put the supplied exercise height 9 cm in row 3 of the copy.
sum(is.na(practice$height_cm))  # Check that the exercise copy has zero missing heights.
mean(practice$height_cm)  # Calculate the exercise mean: 72 divided by 6 is 12 cm.
sum(practice$height_cm)  # Add the six exercise heights to obtain 72 cm.
