【问题标题】:R creating combinations with replacementR创建替换组合
【发布时间】: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


【解决方案1】:

这是使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-04
    • 2019-02-11
    • 1970-01-01
    • 2016-10-01
    • 2016-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多