Menu
Coddy logo textTech

Accessing Vector Elements

Part of the Fundamentals section of Coddy's R journey — lesson 57 of 78.

Now that you can create vectors, you need to know how to retrieve specific values from them. In R, you access vector elements using square brackets [] with the position number of the element you want.

Unlike many programming languages, R uses 1-based indexing - the first element is at position 1, not 0:

fruits <- c("apple", "banana", "cherry", "date")
print(fruits[1])
print(fruits[3])

Output:

[1] "apple"
[1] "cherry"

You can also access multiple elements at once by providing a vector of positions:

scores <- c(85, 92, 78, 95, 88)
print(scores[c(1, 3, 5)])

Output:

[1] 85 78 88

To access the last element of a vector, combine length() with indexing:

numbers <- c(10, 20, 30, 40)
print(numbers[length(numbers)])

Output:

[1] 40
challenge icon

Challenge

Easy

You are provided with the following vector:

temperatures <- c(72, 68, 75, 80, 65, 78, 71)

Using this vector, print the following values in order:

  1. The first temperature
  2. The fourth temperature
  3. The last temperature (use length() to find it dynamically)
  4. The 2nd, 4th, and 6th temperatures together (as a single output)

Your output should be:

[1] 72
[1] 80
[1] 71
[1] 68 80 78

Cheat sheet

Access vector elements using square brackets [] with the position number. R uses 1-based indexing (first element is at position 1):

fruits <- c("apple", "banana", "cherry", "date")
print(fruits[1])  # "apple"
print(fruits[3])  # "cherry"

Access multiple elements by providing a vector of positions:

scores <- c(85, 92, 78, 95, 88)
print(scores[c(1, 3, 5)])  # 85 78 88

Access the last element using length():

numbers <- c(10, 20, 30, 40)
print(numbers[length(numbers)])  # 40

Try it yourself

# Vector of temperatures
temperatures <- c(72, 68, 75, 80, 65, 78, 71)

# TODO: Write your code below
# 1. Print the first temperature

# 2. Print the fourth temperature

# 3. Print the last temperature (use length() to find it dynamically)

# 4. Print the 2nd, 4th, and 6th temperatures together
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals