Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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])
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading