R Program to Access Values in a Vector

Example 1: Access Vector Element in R

In R, we can access elements of a vector using the index number (1, 2, 3 …). For example,

# a vector of string type
languages <- c("Swift", "Java", "R")

# access first element of languages
print(languages[1])  # "Swift"

# access third element of languages
print(languages[3]). # "R"

In the above example, we have created a vector named languages. Each element of the vector is associated with an integer number.

Here, we have used the vector index to access the vector elements

  • languages[1] - access the first element "Swift"
  • languages[3] - accesses the third element "R"

Note: In R, the vector index always starts with 1. Hence, the first element of a vector is present at index 1, second element at index 2 and so on.


Example 2: Access Multiple Vector Element in R

# a vector of string type
languages <- c("Swift", "Java", "R")

# access 1st and 3rd element of languages
print(languages[c(1,3)])  # "Swift" "R"

Output

[1] "Swift" "R"

Here, we have combined two indices using the c() function to access two vector elements at once.

languages[c(1,3)]

The code above accessed and returns 1st and 3rd element of languages.