How to build permutation with some conditions in R [duplicate]

倖福魔咒の 提交于 2019-12-24 01:57:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!