Comparison of vector values

`I wonder how I would like to change this code so that the corresponding values โ€‹โ€‹of both vectors cannot be equal. As an example: if x = (1, 2, 2, 4, 8, 1, 7, 9, 5, 10) and y = (3, 2, 7, 8, 4, 10, 4, 8, 2, 1), then for both vectors they are equal to 2. Does it mean that R can repeat the sampling in this second spot in the vector x until it is the same value in the vector y?

x <- c(1:10) y <- c(1:10) sample_x <- sample(x, length(10), replace = TRUE) z <- sample_x > y` 
+4
source share
3 answers

You can do:

 while(any(x == y)) x <- sample(x) 

Change Now I understand that x and y probably come from a similar call to sample with replace = TRUE , here is an interesting approach that avoids the while . It uses indices and modulo to ensure that the two patterns do not match:

 N <- 1:10 # vector to choose from (assumes distinct values) L <- 20 # sample size - this might be length(N) as in your example n <- length(N) i <- sample(n, L, replace = TRUE) j <- sample(n-1, L, replace = TRUE) x <- N[i] y <- N[1 + (i + j - 1) %% n] 
+7
source
 while (any(ind <- x==y)) x[ind] <- sample(N, sum(ind), TRUE) 

where N is what you choose from (or the maximum number)

The advantage is that if you don't need to try all x , it will converge faster.

+5
source

You can use the permn function from the combinat library to generate all permutations of a vector of length 10.

 ind <- permn(10) xy_any_equal <- sapply(ind, function(i) any(x[i] == y)) if(sum(xy_any_equal) < length(xy_any_equal)) x_perm <- x[head(ind[!xy_any_equal],1)[[1]]] exists(x_perm) 
0
source

Source: https://habr.com/ru/post/1495241/


All Articles