To access items in a vector in R, you can use indexing and slicing operations.
In this example,
my_vector
containing some elements.[]
and specify the index of the element we want to access.# Create a vector
my_vector <- c('apple', 'banana', 'cherry', 'date')
# Access single element by index (e.g., index 2)
accessed_element <- my_vector[2]
# Print accessed element
print(accessed_element)
[1] "banana"
In this example,
my_vector
containing some elements.[]
to access multiple elements from the vector.# Create a vector
my_vector <- c('apple', 'banana', 'cherry', 'date')
# Access multiple elements by indices (e.g., indices 1 and 3)
accessed_elements <- my_vector[c(1, 3)]
# Print accessed elements
print(accessed_elements)
[1] "apple" "cherry"
In this example,
my_vector
containing numeric elements.[]
to access elements that satisfy the condition.# Create a numeric vector
my_vector <- c(10, 20, 30, 40, 50)
# Access elements greater than 30
accessed_elements <- my_vector[my_vector > 30]
# Print accessed elements
print(accessed_elements)
[1] 40 50
In this tutorial, we learned How to Access Items in a Vector in R language with well detailed examples.