R Program to Access Values in a Vector

[This article was first published on R feed, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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.

To leave a comment for the author, please follow the link and comment on their blog: R feed.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)