如何在R中找到包含重复元素的向量的唯一排列?
我们可以使用combinat包中的permn函数来查找排列,但是如果向量中包含重复元素,则结果将不包含唯一排列,因此,我们需要将unique函数与permn函数一起使用。例如,如果我们有一个向量1, 2, 1,则排列将是(1 2 1), (1 1 2), (1 1 2), (1 2 1), (2 1 1), (2 1 1),而唯一排列将是(1 2 1), (1 1 2), (2 1 1)。
示例
x1<-c(1,2,1,2) x1
输出
[1] 1 2 1 2
查找所有排列:
permn(x1)
[[1]] [1] 1 2 1 2 [[2]] [1] 1 2 2 1 [[3]] [1] 1 2 2 1 [[4]] [1] 2 1 2 1 [[5]] [1] 2 1 1 2 [[6]] [1] 1 2 1 2 [[7]] [1] 1 1 2 2 [[8]] [1] 1 1 2 2 [[9]] [1] 1 1 2 2 [[10]] [1] 1 1 2 2 [[11]] [1] 1 2 1 2 [[12]] [1] 2 1 1 2 [[13]] [1] 2 1 2 1 [[14]] [1] 1 2 2 1 [[15]] [1] 1 2 2 1 [[16]] [1] 1 2 1 2 [[17]] [1] 2 1 1 2 [[18]] [1] 2 1 2 1 [[19]] [1] 2 2 1 1 [[20]] [1] 2 2 1 1 [[21]] [1] 2 2 1 1 [[22]] [1] 2 2 1 1 [[23]] [1] 2 1 2 1 [[24]] [1] 2 1 1 2
查找唯一排列:
unique(permn(x1))
[[1]] [1] 1 2 1 2 [[2]] [1] 1 2 2 1 [[3]] [1] 2 1 2 1 [[4]] [1] 2 1 1 2 [[5]] [1] 1 1 2 2 [[6]] [1] 2 2 1 1
示例
x2<-c(0,1,0) permn(x2)
[[1]] [1] 0 1 0 [[2]] [1] 0 0 1 [[3]] [1] 0 0 1 [[4]] [1] 0 1 0 [[5]] [1] 1 0 0 [[6]] [1] 1 0 0
unique(permn(x2))
[[1]] [1] 0 1 0 [[2]] [1] 0 0 1 [[3]] [1] 1 0 0
广告