如何在R中的某些条件下建立置换 [英] How to build permutation with some conditions in R

查看:64
本文介绍了如何在R中的某些条件下建立置换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是R的新手,我有些困惑.假设我有一个向量c(1,2,3,4,5,6).我想生成包含四个元素的排列,每个排列都应包含1和5.谢谢.

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.

推荐答案

您可以使用gtools软件包中的="nofollow noreferrer"> permutations() 以获取置换,然后

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))

输出:

# 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
 # ...

这篇关于如何在R中的某些条件下建立置换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆