首页 > 解决方案 > R创建替换组合

问题描述

我有一个小例子,如下所示:

df1 = data.frame(Id1=c(1,2,3))

我想获取所有替换组合的列表,如下所示:

在此处输入图像描述

到目前为止,我已经看到了以下函数,它们产生了上表的某些部分:

a) 组合功能

t(combn(df1$Id1,2)) 

# Does not creates rows 1,4 and 5 in the above image

b) expand.grid 函数

expand.grid(df1$Id1,df1$Id1) 

# Duplicates rows 2,3 and 5. In my case the combination 1,2 and 2,1 
#are the same. Hence I do not need both of them at the same time.

c) CJ 函数(来自 data.table)

#install.packages("data.table")
CJ(df1$Id1,df1$Id1)

#Same problem as the previous function

供您参考,我知道在 python 中我可以使用 itertools 包做同样的事情(链接在这里:https ://www.hackerrank.com/challenges/itertools-combinations-with-replacement/problem )

有没有办法在 R 中做到这一点?

标签: rdata-manipulation

解决方案


这是一种替代方法expand.grid,方法是为每个组合创建一个唯一key的,然后删除重复项

library(dplyr)

expand.grid(df1$Id1,df1$Id1) %>%
   mutate(key = paste(pmin(Var1, Var2), pmax(Var1, Var2), sep = "-")) %>%
   filter(!duplicated(key)) %>%
   select(-key) %>%
   mutate(row = row_number())


#  Var1 Var2 row
#1    1    1   1
#2    2    1   2
#3    3    1   3
#4    2    2   4
#5    3    2   5
#6    3    3   6

推荐阅读