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

Permute the position of a subset of a vector

I want to permute a subset of a vector.

For example, say I have a vector (x) and I select a random subset of the vector (e.g., 40% of its values).

What I want to do is output a new vector (x2) that is identical to (x) except the positions of the values within the random subset are randomly swapped.

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

For example:

  • x = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
  • random subset = 1, 4, 5, 8
  • x2 could be = 4, 2, 3, 8, 1, 6, 7, 5, 9, 10

Here’s an an example vector (x) and how I’d select the indices of a random subset of 40% of its values. Any help making (x2) would be appreciated!

x <- seq(1,10,1)
which(x%in%sample(x)[seq_len(length(x)*0.40)])

>Solution :

First draw a sample of proportion p from the indices, then sample and re-assign elements with that indices.

f <- \(x, p=0.4) {
  r <- sample(seq_along(x), length(x)*p)
  x[r] <- sample(x[r])
  `attr<-`(x, 'subs', r)  ## add attribute w/ indices that were sampled
}

set.seed(42)
f(x)
#  [1]  8  2  3  4  1  5  7 10  6  9
# attr(,"subs")
# [1]  1  5 10  8

Data:

x <- 1:10
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