To rotate elements in a list in R, you can use list indexing and concatenation.
In this example,
numbers
with integer values.numbers <- c(1, 2, 3, 4, 5)
distance <- 2
rotated_numbers <- c(numbers[(distance + 1):length(numbers)], numbers[1:distance])
cat('Rotated list:', rotated_numbers)
Rotated list: 4 5 1 2 3
In this example,
words
with string values.words <- c('apple', 'banana', 'cherry', 'date', 'elderberry')
distance <- 3
rotated_words <- c(words[(distance + 1):length(words)], words[1:distance])
cat('Rotated list:', rotated_words)
Rotated list: date elderberry apple banana cherry
In this tutorial, we learned How to Rotate Elements in a List in R language with well detailed examples.