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

Time:05-17

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.

CodePudding user response:

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])
}

CodePudding user response:

Using seq, f gives you the desired subset for a specified vector v, of which you would like to subset l elements with a starting point at the nth position.

f <- function(v, n, l) v[seq(n - 1, length.out = l) %% length(v)   1]

output

f(v, n = 4, l = 3)
#[1] "D" "A" "B"

f(v, n = 3, l = 4)
#[1] "C" "D" "A" "B"

f(v, n = 2, l = 5)
#[1] "B" "C" "D" "A" "B"
  • Related