To get the first N items from a vector in R, you can use array indexing.
In this example,
# Define a vector containing elements
vector <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
# Specify the number of items to retrieve (N)
N <- 5
# Retrieve the first N items from the vector
first_N_items <- vector[1:N]
# Print the first N items
print(first_N_items)
[1] 1 2 3 4 5
In this example,
# Define a character vector
char_vector <- c("apple", "banana", "orange", "grape", "kiwi")
# Retrieve the first three items from the character vector
first_three_items <- char_vector[1:3]
# Print the first three items
print(first_three_items)
[1] "apple" "banana" "orange"
In this tutorial, we learned How to get First N Items from a Vector in R language with well detailed examples.