Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

vector

subset

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.

like image 378
Miquel Avatar asked Oct 18 '25 03:10

Miquel


2 Answers

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"
like image 191
Maël Avatar answered Oct 20 '25 18:10

Maël


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])
}
like image 34
Paul Avatar answered Oct 20 '25 16:10

Paul