Search code examples
rvectorsubset

Subset a vector and retrieve first elements if exceed the length in R


Imagine I have a vector like this one:

c("A", "B", "C", "D")

there are 4 positions. If I make a sample with size 1 I can get 1, 2, 3 or 4. What I want is to be able to subset of length 3 of that vector according its order, for example, if I get 2:

c("B", "C", "D")

If I get 3:

c("C", "D", "A")

If I get 4:

c("D","A", "B")

So that's the logic, the vector is sorted and the last elements connects with the first element when I subset.


Solution

  • I think I got it!

    v <- c("A", "B", "C", "D")
    p <- sample(1:length(v), 1)
    r <- c(v[p:length(v)])
    c(r, v[!(v %in% r)])[1:3]
    
    

    And the outputs:

    v <- c("A", "B", "C", "D") # your vector
    
    r <- c(v[2:length(v)])
    c(r, v[!(v %in% r)])[1:3]
    #> [1] "B" "C" "D"
    
    r <- c(v[3:length(v)])
    c(r, v[!(v %in% r)])[1:3]
    #> [1] "C" "D" "A"
    
    r <- c(v[4:length(v)])
    c(r, v[!(v %in% r)])[1:3]
    #> [1] "D" "A" "B"
    

    Created on 2022-05-16 by the reprex package (v2.0.1)

    Wrapped in a function:

    f <- function(v, nth) {
      r <- c(v[nth:length(v)])
      return(c(r, v[!(v %in% r)])[1:3])
    }