To rotate items in a vector in R, you can use the combination of negative indexing and concatenation.
In this example,
# Define a vector containing elements
vector <- c(1, 2, 3, 4, 5)
# Specify the number of positions to rotate the items to the left
rotate_by <- 2
# Extract the rotated elements using negative indexing
rotated_elements <- vector[-(1:rotate_by)]
# Concatenate the rotated elements with the elements from the beginning to the specified position
rotated_vector <- c(rotated_elements, vector[1:rotate_by])
# Print the rotated vector
print(rotated_vector)
[3, 4, 5, 1, 2]
In this example,
# Define a vector containing elements
vector <- c(1, 2, 3, 4, 5)
# Specify the number of positions to rotate the items to the right
rotate_by <- 2
# Extract the rotated elements using negative indexing
rotated_elements <- vector[(length(vector) - rotate_by + 1):length(vector)]
# Concatenate the rotated elements with the elements from the beginning to the specified position
rotated_vector <- c(rotated_elements, vector[1:(length(vector) - rotate_by)])
# Print the rotated vector
print(rotated_vector)
[4, 5, 1, 2, 3]
In this tutorial, we learned How to Rotate Items in a Vector in R language with well detailed examples.