Chapter 2: R vectors, names and selecting values
How do I name an R vector and select values by position or name?
An R numeric vector stores numbers in order. Combine them with c() and select the third with [3]. Here we also name six seedling heights.
On this page
In chapter 1, you stored the heights of six seedlings. Now I want to look at just three: A, D and F. We will give each value a name, pick those three seedlings from the original vector, and draw the result below.

Square brackets may look unfamiliar at first. Start by asking for the third value and checking that you get 9. Once that works, try selecting three values together.
What are a vector, an element, a position and a name?
Imagine writing six seedling heights in a row: 8, 11, 9, 14, 12, 18. Saving those numbers together in R gives you a numeric vector. Each number is one element.
Count from the left: 8 is in position 1, 11 in position 2 and 9 in position 3. A position number is also called an index. We will label the seedlings A through F so we can ask for a height by name. This table shows the same six heights three ways.
| Position (starting at 1) | Seedling name | Height (cm) |
|---|---|---|
| 1 | A | 8 |
| 2 | B | 11 |
| 3 | C | 9 |
| 4 | D | 14 |
| 5 | E | 12 |
| 6 | F | 18 |
A data type tells R how to store a value, for example as a number or as text. All heights in this numeric vector have the same numeric type; A through F are names attached to them. height_cm names the whole collection, like a label on a storage box.
In RStudio, choose File → New File → R Script and save the code file as vectors.R. Select a short piece of code and click Run; read the result in Console. c() combines values in order, <- saves the result under a name, and print() displays it.
The number after a function runs is its returned value: simply its answer. In this chapter, print() displays that answer in Console.
How do I store six heights with their seedling names?
Put pairs such as A = 8 inside c() to create a named numeric vector.
This article uses simulated example data.
Inside c(), A = 8 attaches the name A to the value 8. Commas separate the seedlings. length() counts the elements, giving 6 here; names() displays their names. These lines display the names above their heights, then the count 6, then the six names.
height_cm <- c(A = 8, B = 11, C = 9, D = 14, E = 12, F = 18)
print(height_cm)
length(height_cm)
names(height_cm)
A B C D E F
8 11 9 14 12 18
[1] 6
[1] "A" "B" "C" "D" "E" "F"
I used short letters so you can match each printed value to a label on the chart. You can use your own sample IDs later; a distinct name for each seedling makes them easy to find.
How do I select the third value or several positions?
height_cm[3] returns C at 9 cm; height_cm[c(1, 4, 6)] returns A, D and F at 8, 14 and 18 cm.
Square brackets [ ] select from a collection. height_cm[3] takes its third element, 9 with the name C. To select several positions, put them together with c(1, 4, 6) inside the brackets. selected is our new name for that selection; height_cm still stores all six heights.
height_cm[3]
selected <- height_cm[c(1, 4, 6)]
print(selected)Count across the table before running the selection: the third position contains C and 9. Read this output after running the three lines above.
Output
C
9
A D F
8 14 18

How do I select values when I know their names?
Use a quoted name inside brackets, such as height_cm["C"], or combine names with height_cm[c("B", "E")].
Double quotes tell R that "C" is text used as a name. Match the C shown by names(height_cm), using straight keyboard quotes. Run these three lines in order to select one name, two names and then a different order.
height_cm["C"]
height_cm[c("B", "E")]
height_cm[c("F", "A")]
These return C=9; B=11 and E=12; then F=18 and A=8. The last line also shows how selection controls the order: put "F" first to receive F first. Match the capital letters shown by names(height_cm).
How do I plot the three selected seedlings?
Pass selected to barplot(); R uses its element names as labels and its values as bar heights.
barplot() draws bars: a taller bar represents a larger value. selected holds the three heights we picked. ylim = c(0, 20) sets the vertical range from 0 to 20; main sets the graph title; xlab and ylab set the axis titles; col sets the fill color. NA is R’s marker for a missing value. In the border drawing setting, border = NA omits bar outlines.
barplot(selected, col = "#0066CC", border = NA,
ylim = c(0, 20), xlab = "Seedling", ylab = "Height (cm)",
main = "Selected seedlings: A, D, F")
The chart appears in Plots. I fixed the vertical range at 0–20 cm so you can compare it with the six-seedling chart. col sets the blue fill and border = NA removes bar outlines. Keep those settings for now and watch which values enter the plot.
What should I check if I get NA or an object error?
NA marks a value that is unavailable. Here a lowercase c or position 7 has no matching height, so the selection produces NA. Check the name and position, then select again.
Run names(height_cm) and length(height_cm) to check spelling and the available positions, then check that you ran the line creating the vector.
Here, height_cm["c"] and height_cm[7] return NA: the name needs a capital "C", and position 7 exceeds the six available positions. For object 'height_cm' not found, run the assignment at the start. Use ordinary straight quotes and brackets; height_cm["C"] should then give 9.
Can you select B, C and E and check their mean?
B, C and E have heights 11, 9 and 12 cm: their sum is 32 and their mean is 32 / 3, about 10.6667 cm.
Save your selection as practice, then check it with mean() from chapter 1. Plot practice and change the title to B, C, E. Open the solution when you are ready to compare.
practice is the name you give these three selected heights. sum() adds the values inside its brackets; mean() divides their sum by their count. There are three values here, so check the mean by dividing 32 by 3.
Show the exercise solution
practice <- height_cm[c("B", "C", "E")]
print(practice)
sum(practice)
mean(practice)
barplot(practice, col = "#0066CC", border = NA,
ylim = c(0, 20), xlab = "Seedling", ylab = "Height (cm)",
main = "Selected seedlings: B, C, E")The console shows 11, 9, 12, followed by 32 and approximately 10.66667. The full vector still has a mean of 12 cm; this calculation uses your selected three seedlings.
How do I download and rerun the complete example?
The working directory is the folder where R currently looks for files and saves them. In RStudio choose Session → Set Working Directory → Choose Directory, select the folder containing lesson.R and export.R, then run source("export.R"). source() runs the code in the named file from the start. PNG is an image file made of tiny picture dots called pixels. PDF is a document format suited to printing and enlargement. CSV stores table columns separated by commas and opens in spreadsheet software. Exporting means saving results in files like these.
Download lesson.R to run the selections and chart. With export.R in the same folder, you can also create two PNGs, one PDF and two CSV files.
height_cm <- c(A = 8, B = 11, C = 9, D = 14, E = 12, F = 18)
print(height_cm)
print(length(height_cm))
print(names(height_cm))
print(height_cm[3])
selected <- height_cm[c(1, 4, 6)]
print(selected)
print(height_cm[c("B", "E")])
print(height_cm[c("F", "A")])
barplot(selected, col = "#0066CC", border = NA,
ylim = c(0, 20), xlab = "Seedling", ylab = "Height (cm)",
main = "Selected seedlings: A, D, F")
practice <- height_cm[c("B", "C", "E")]
print(practice)
print(sum(practice))
print(mean(practice))
In RStudio, use Session → Set Working Directory → Choose Directory to select that folder, then run source("export.R"). PNGs are 1200 × 800 pixels; the PDF is 7.5 × 5 inches. This example was run with R 4.5.3 and standard R functions.
Once you can replace A, D, F with B, C, E and recognize them on the chart, you can pick the part of a dataset you need. Keep these bracket examples nearby while the syntax becomes familiar. Next, we will put sample names and heights into a data table so you can view them together.
Where can I check how vector selection works?
Sections 2.1 and 2.7 of the R manual explain vectors and selection. The names() help page describes element names.
Learn R

