Nicolas H
Nicolas H

Reputation: 545

Switch the some of the vector in R

For example, I have a vector below:

a = c(1,1,1,1,1,2,2,2,3,3,3,3)

Now I want to randomly pick 4 of the elements from all the elements then change them into different value, for instance,

if the elements I pick is 1, 1, 2, 3, then I need to change them randomly , like, 2, 3, 1, 2

The resulting vector is the following

a' = c(1,2,3,1,1,2,1,2,3,3,3,2)

No idea how to make this.

Upvotes: 2

Views: 84

Answers (2)

akrun
akrun

Reputation: 887048

May be this function helps

# @param vec - input vector
# @param n - number of values to replace
# @param n1 - number of unique value threshold
# @return replaced sampled vector   

sample_fn <- function(vec, n, n1) {
       
            flag <- TRUE
            while(flag) {
                  # // sample on the positions
                  pos <- sample(seq_along(vec), n, replace = FALSE)
                  print(pos)
                  # // extract the values based on the position index
                  as <- vec[pos]
                  # // get the unique values
                  un1 <- unique(as)
                  print(un1)
                  if(length(un1) > n1)
                  flag <- FALSE
                  }
                  
           # // sample the unique and set it as names of unique
           # // use named vector to match and replace
           # // assign the output back to the same positions in the vector
           vec[pos] <- setNames(sample(un1), un1)[as.character(as)]
           vec      
       
              }
sample_fn(a, 4, 2)
#[1] 10  1 12  2
#[1] 3 1
#[1] 1 8 4 3
#[1] 1 2
#[1]  7 11  4 12
#[1] 2 3 1
# [1] 1 1 1 2 1 2 3 2 3 3 1 1


       

Upvotes: 1

ThomasIsCoding
ThomasIsCoding

Reputation: 101247

I am not sure if the values for random replacement are also from a. If so, the code below might be an option

replace(a,sample(seq_along(a),4),sample(unique(a),4,replace = TRUE))

Upvotes: 0

Related Questions