Chapter 4: Open a CSV and find a missing height
How can I read saved heights and handle a blank entry?
Read the CSV into R, find C's blank height and plot the five recorded seedlings. Their heights sum to 63 cm and average 12.6 cm.
On this page
In the first three chapters we typed seedling names and heights into code. This time I have saved the table in a file. You will open it in R, find C's blank height and draw the other five seedlings.

What are a file, a folder and a CSV?
A file is a saved piece of information. A folder keeps files together in one place. Our file is called data.csv: data is its name, and .csv identifies the CSV format. A CSV uses commas to separate entries on a line, and a new line starts the next row.
Here is the file's content. The first line names the two columns. Each later line records one seedling. In height_cm, the underscore joins the words and cm means centimetres. The line for C ends just after its comma, leaving the height blank.
seedling,height_cm
A,8
B,11
C,
D,14
E,12
F,18
Create a folder called bopbun-r04 in your computer's Downloads folder. Download data.csv, lesson.annotated.en.R and export.annotated.en.R into it. If your browser first places them directly in Downloads, move them into bopbun-r04 using your file manager. Check all three filenames against the links.
If you copy a complete program from this page, choose File → New File → R Script in RStudio, paste the code and save it with the exact displayed filename in bopbun-r04. Choose File → Save with Encoding → UTF-8 when saving. UTF-8 is a way of saving text that keeps these comments readable in different languages. Save the two programs as separate files, alongside data.csv.
How do I tell R where to find the file?
Set the folder containing data.csv as R's working directory: the folder R currently uses to find files and save this lesson's results.
Open RStudio and choose File → Open File to open lesson.annotated.en.R. A .R file holds R commands and is called a script. Its commands appear in the code editor. Choose Session → Set Working Directory → Choose Directory and select bopbun-r04. The Console is the area where commands produce written results. The > in Console shows that R is waiting for input. Click after it, enter each of the next two lines and press Enter at the end of each line. Enter these location checks, the exercise's final original-cell check and the final export command in Console. For the other steps, select the corresponding lines in lesson.annotated.en.R and click Run.
Check the location first. getwd() shows the full location of the current folder. file.exists() checks for the named file there. A function is a named operation; parentheses hold its inputs. Empty parentheses mean this call needs no extra input. Straight double quotes surround the filename. Keep the dots and parentheses as shown.
TRUE means yes and FALSE means no; both use capitals. After these lines, you should see your own folder's location, followed by [1] TRUE. The [1] marks the first displayed value.
Enter in R
Use the annotated learning and export files linked here with data.csv. A comment is a note for the reader: outside quotes, # starts a note through the end of that line. The # inside the quoted color "#0066CC" belongs to the color text. R executes the commands beside the comments.
getwd() # Show the folder R is currently using.file.exists("data.csv") # Check whether data.csv is in that folder.If you see FALSE, check that the selected folder contains data.csv. Look for a browser-added name such as data (1).csv or an extra .txt ending. Select the folder containing the intended file and repeat the check until it returns TRUE.
How do I turn the CSV into a table in R?
read.csv() reads the file into a data frame: the row-and-column table from Chapter 3. Each row records one seedling, and each column holds one kind of information. We give this table the name seedlings.
The arrow <- saves the table on the right under the name on the left. R calls a piece of information such as this table an object. seedlings is the name we use to refer to it. print() displays it, nrow() counts rows and ncol() counts columns. Match the spelling and case in the code.
na.strings is a setting, also called an argument, for reading the file. The = supplies its value. c() puts values together in order, separated by commas. "" is empty text, and "NA" is the pair of letters that might appear in a file. This setting reads both as R's missing-entry marker, NA. NA marks information that is currently missing; a measured height of zero is recorded as the number 0.
Enter in R
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.Expected text result
seedling height_cm
1 A 8
2 B 11
3 C NA
4 D 14
5 E 12
6 F 18
[1] 6
[1] 2
Check six rows, two columns and NA beside C in row 3. The small numbers 1–6 on the left are row labels. The column names are seedling and height_cm.
How do I find the seedling with a missing height?
is.na() checks each entry for missing information. We save the results as missing. Here TRUE marks a missing entry and FALSE marks a recorded one.
Read seedlings$height_cm as “the height_cm column inside seedlings”. The $ is followed by the complete column name. The check returns six answers in the original A–F order. When adding these answers, sum() counts TRUE as 1 and FALSE as 0. Thus sum(missing) counts the gaps. Square brackets [missing] select the TRUE positions from the name column, giving C.
Enter in R
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.Expected text result
[1] FALSE FALSE TRUE FALSE FALSE FALSE
[1] 1
[1] "C"
Only the third position is TRUE. There is one gap, belonging to C.
How can I average the recorded heights?
Use na.rm = TRUE to skip missing entries for this calculation and average the five recorded heights. A mean is the sum divided by the number of values used: 63 divided by 5 gives 12.6.
mean() calculates the mean. With the missing entry included, its default result is NA. The na.rm setting controls skipping missing entries for this calculation; TRUE turns it on. The comma separates the height column from that setting. sum() accepts the same setting.
Enter in R
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.Expected text result
[1] NA
[1] 12.6
[1] 63
Check the three results: NA, 12.6 and 63. C keeps its NA in the original table; this mean describes the five seedlings with recorded heights.
How do I draw only the five recorded heights?
Put the recorded rows into a table named observed, then use it to draw five bars.
The ! symbol reverses TRUE and FALSE for every position. So !missing is TRUE at recorded positions, and sum(!missing) counts five of them. Inside a table's square brackets, the part before the comma selects rows and the part after it selects columns. seedlings[!missing, ] keeps the selected rows; leaving the column part empty keeps every column.
Enter in R
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.Expected text result
[1] 5
seedling height_cm
1 A 8
2 B 11
4 D 14
5 E 12
6 F 18
The row labels still show their original numbers 1, 2, 4, 5 and 6. The five rows now describe A, B, D, E and F.
barplot() draws the bars. Its first input supplies heights and names.arg supplies their names. col sets blue, border = NA omits outlines and ylim = c(0, 20) sets a vertical range from 0 to 20. xlab and ylab supply axis titles; main supplies the chart title. Text inside the quotes appears on the chart.
Enter in R
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.Look in RStudio's Plots area. Find A at 8 cm and F at 18 cm, then check B, D and E against the table. You should have the same five bars as the opening figure.
Exercise: what changes when a copy receives C's supplied height?
For this exercise, I supply C's original simulated height: 9 cm. Make a copy of the original six-row seedlings table called practice, put 9 in row 3's height cell, and check the missing-entry count, mean and sum. Try it first, then open the answer.
Open the exercise answer
practice <- seedlings makes the copy. In practice[3, "height_cm"] <- 9, the part before the comma selects row 3, and the quoted column name selects its height cell. The arrow puts 9 there. The last line checks the same cell in the original table. Enter that final check in Console.
Enter in R
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.seedlings[3, "height_cm"] # Check that C is still NA in the original table.Expected text result
[1] 0
[1] 12
[1] 72
[1] NA
The results are 0, 12, 72 and NA. The copy contains six heights; 72 divided by 6 gives 12. The original table still shows NA for C, and the blank in the input CSV is retained. For a missing real record, check the original records before choosing how to proceed with the analysis.
Can I copy the complete learning program?
This is the complete learning program, including the exercise. Save it as lesson.annotated.en.R. The earlier short blocks correspond to the reading, missing-entry, calculation, plot and exercise parts of this file. The two folder checks and the final check of the original C cell are extra Console checks. For step-by-step study, select the matching lines and click Run after reading their explanations. For all output files together, use the export program below.
# 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.How do I save the results and use the downloads?
Save this complete exporter as export.annotated.en.R in the same folder. With that folder still selected as the working directory, enter the following line in Console. source() runs this exporter, which runs the matching learning file. Re-running updates the four named result files in the dedicated lesson folder.
Enter in R
How does R start and finish each image file?
png() starts writing a PNG image; later plotting commands draw into that file. width=1200 and height=800 are pixel counts, and res=160 means 160 pixels per inch. pointsize=12 sets the base text size to 12 typographic points, with 72 points in an inch. bg="white" sets the background and family="sans" requests a sans-serif font. R calls the place currently receiving a drawing a graphics device. dev.off() finishes that output and closes the device. It leaves the saved file available to open.
Why does the learning file run twice?
source() reads and runs a saved script. Its quoted filename must match the annotated learning file beside data.csv. encoding="UTF-8" tells R how that text was saved. print.eval=TRUE asks R to display the results produced by the expressions, so you can check the numbers in Console. After finishing the PNG, pdf() opens a second output. This time width=7.5 and height=5 are inches. Helvetica is the PDF font, and timestamp=FALSE leaves changing date fields out. Running the same learning file again draws the same five bars into the PDF, then dev.off() finishes it.
How are the two result tables saved?
write.csv() writes a table to the quoted CSV filename. observed supplies the five recorded rows; practice supplies the six-row exercise copy. row.names=FALSE leaves out an extra column of R row labels. This shorter annotated exporter creates the same four figure/table files as the original exporter. The original export.R download also includes automatic checks of rows and numerical results. The input data.csv and the original C value remain unchanged.
png("recorded-heights.png", width = 1200, height = 800, res = 160, # Open a 1200 by 800 pixel PNG output at 160 pixels per inch. pointsize = 12, bg = "white", family = "sans") # Use 12-point sans-serif text on a white background.source("lesson.annotated.en.R", encoding = "UTF-8", print.eval = TRUE) # Run the learning file using UTF-8 text and display its results.dev.off() # Finish writing the current image file.pdf("recorded-heights.pdf", width = 7.5, height = 5, pointsize = 12, # Open a 7.5 by 5 inch PDF page with 12-point text. family = "Helvetica", bg = "white", timestamp = FALSE) # Use Helvetica on white and omit changing PDF date fields.source("lesson.annotated.en.R", encoding = "UTF-8") # Draw the same learning chart into this PDF.dev.off() # Finish writing the PDF file.write.csv(observed, "observed.csv", row.names = FALSE) # Save the five recorded rows without an extra row-label column.write.csv(practice, "practice.csv", row.names = FALSE) # Save the six-row exercise copy to its own CSV.source("export.annotated.en.R", encoding = "UTF-8") # Run the matching annotated exporter using UTF-8 text.Open bopbun-r04 in your file manager afterward. recorded-heights.png is an image and recorded-heights.pdf is a printable document. The PNG is 1200 × 800 pixels; the PDF is 7.5 × 5 inches. observed.csv holds five recorded heights, and practice.csv holds the exercise copy. Running the export again updates results with these filenames, so use the dedicated lesson folder. This example ran with R 4.5.3 and its standard tools.
You have the main steps when you can open the file, locate C's gap and explain why five heights were used in the mean. The next chapter is planned to practise selecting, ordering and organising records.
Annotated programs and actual run text
- lesson.annotated.en.R — Complete learning program with the same commands and localized line comments.
- export.annotated.en.R — Complete shorter exporter shown above; runs the matching learning program and saves four results.
- annotated-console.en.txt — Actual text recorded while executing this annotated export.
Code, data and results
Keep each pair together: original export.R calls lesson.R; an annotated exporter calls its same-language annotated learning file. Both routes read data.csv and save the four named outputs. The original downloads remain available below.
These are the code, data and result files for this chapter.
- lesson.R — Commands to run one short step at a time.
- export.R — Runs the lesson and saves the figures and result tables.
- data.csv — Input table; C has a deliberately blank height.
- observed.csv — The five rows with recorded heights.
- practice.csv — Exercise table after C receives the supplied value 9.
- recorded-heights.png — The complete result image.
- recorded-heights.pdf — The same figure as a printable PDF.
- console-output.txt — Recorded text from executing the export code.
- Usage license · LICENSE.txt — Reuse terms for the code, data and figure, including font notices.
Learn R

