r - 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 中做到这一点?
解决方案
这是一种替代方法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
推荐阅读
- node.js - 存储文件(pdf),因此只有经过身份验证的用户才能访问它们(使用 nextjs)
- javascript - 如何按名称查找频道 DiscordJS 12
- windows - 恢复除一个文件夹外的所有文件
- angular - 没有提供者的角度服务注入错误
- json - 调用 API 返回预期的 JSONArray,找到 JSONObject
- google-apps-script - 在 Google 表格中搜索两次之间的命名范围并填充差异
- android - 如何正确地将数据解析到我的改造客户端以执行发布请求
- angular - Angular NX mono repo:如何包含来自 node_modules 的文件
- arrays - 测试我的排序算法错误:控制到达非空函数的结尾
- google-bigquery - BigQuery 客户端网址