【问题标题】:R - Creating a random combination for elemens of two vectorR - 为两个向量的元素创建随机组合
【发布时间】:2019-06-14 18:40:55
【问题描述】:
a <- rnorm(10)

b <- sample(a,18,replace = T)

对于a 的每个元素,我想从向量b 中随机分配一个值。这样我将对向量“a”的所有元素进行组合。它会是这样的:

combinations <- data.table(first=a ,second=sample(b,length(a)))

我真正想要的与 data.table combinations 有点不同。我想获得一组组合,其中非行具有重复值。

编辑:combinations$first[i] 和combinations$second[i] 在上面的代码中可能相等。我想要的是让组合$first[i] 和combinations$second[i] 相等的情况变得不可能。

注意:我会为大向量做这个,所以它需要很快。

【问题讨论】:

  • 我不知道combinations 有什么问题。每行已经是唯一的,因为 a (combinations$first) 具有非唯一值
  • 我有点困惑。 b 本身不只是 a 的随机样本吗?如果您不想重复来自a,那么也许您只需要replace = F。我不是 100% 清楚您在寻找什么。

标签: r vector random combinations


【解决方案1】:

您可以按如下方式分组采样

library(data.table)
set.seed(0L)
a <- LETTERS[1L:10L]
output <- data.table(first=a)[, .(second=sample(setdiff(a, first), .N)), by=.(first)]

如果需要随机行排序,可以运行output[sample(.N)]

输出:

    first second
 1:     A      J
 2:     B      D
 3:     C      E
 4:     D      G
 5:     E      J
 6:     F      B
 7:     G      J
 8:     H      J
 9:     I      F
10:     J      F

【讨论】:

    猜你喜欢
    • 2016-12-24
    • 2017-04-24
    • 1970-01-01
    • 1970-01-01
    • 2016-05-20
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多