问题
I am new to R and I am a little confused. Suppose I have a vector of c(1,2,3,4,5,6). I would like to generate permutations with four elements and every permutation should involve 1 and 5. Thank you.
回答1:
You can use permutations() from the gtools
package to get the permuations, and filter_all() from dplyr
to get just the ones with 1 and 5:
library(gtools)
library(dplyr)
data <- c(1, 2, 3, 4, 5, 6)
permutations(n = 6, r = 4, v = data, repeats.allowed = FALSE) %>%
as_tibble() %>%
filter_all(any_vars(. == 5)) %>%
filter_all(any_vars(. == 1))
Output:
# A tibble: 144 x 4
V1 V2 V3 V4
<dbl> <dbl> <dbl> <dbl>
1 1 2 3 5
2 1 2 4 5
3 1 2 5 3
4 1 2 5 4
5 1 2 5 6
# ...
来源:https://stackoverflow.com/questions/52675487/how-to-build-permutation-with-some-conditions-in-r