【发布时间】:2019-04-18 12:04:23
【问题描述】:
我有一个像下面这样的小例子:
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 中做到这一点?
【问题讨论】:
-
我认为您要求的是“独特组合”而不是“替换”,这对我来说是关于采样并且意味着不同的东西。使用该搜索词,您会看到已经存在一些相关问题,例如stackoverflow.com/questions/49563565/…
-
@arvi1000 你是对的。混淆这两者是我的坏事。感谢您指出我正确的方向。
标签: r data-manipulation