【问题标题】:Random sequence from fixed ensemble that contains at least one of each character来自固定合奏的随机序列,至少包含每个字符中的一个
【发布时间】:2014-12-08 14:54:49
【问题描述】:

我正在尝试从包含每个字符至少一个的固定数量的字符生成随机序列。

例如有合奏

m = letters[1:3]

我想创建一个包含 N = 10 个元素的序列,每个元素至少包含一个 m 字符,例如

a
a
a
a
b
c
c
c
c
a

我尝试使用sample(n,N,replace=T),但这种方式也是一个类似的序列

a
a
a
a
a
c
c
c
c
a

可以生成不包含b

【问题讨论】:

标签: r random sample


【解决方案1】:
f <- function(x, n){
    sample(c(x, sample(m, n-length(x), replace=TRUE)))
}
f(letters[1:3], 5)
# [1] "a" "c" "a" "b" "a"
f(letters[1:3], 5)
# [1] "a" "a" "b" "b" "c"
f(letters[1:3], 5)
# [1] "a" "a" "b" "c" "a"
f(letters[1:3], 5)
# [1] "b" "c" "b" "c" "a"

【讨论】:

  • 打败我。似乎是没有大惊小怪的合乎逻辑的方式。
  • 又一个宝石答案
  • 这个工作的原因(如果有人想知道)是因为外部sample 没有replace=TRUE,同时它总是包含x(所有唯一值)
【解决方案2】:

Josh O'Briens 的回答是一个很好的方法,但没有提供太多的输入检查。既然我已经写过了,它不妨提出我的答案。这几乎是一回事,但需要检查一些事情,例如只考虑独特的物品,并确保有足够的独特物品来保证您至少获得每个物品。

at_least_one_samp <- function(n, input){
  # Only consider unique items.
  items <- unique(input)

  unique_items_count <- length(items)
  if(unique_items_count > n){
    stop("Not enough unique items in input to give at least one of each")
  }

  # Get values for vector - force each item in at least once
  # then randomly select values to get the remaining.
  vals <- c(items, sample(items, n - unique_items_count, replace = TRUE))
  # Now shuffle them
  sample(vals)
}

m <- c("a", "b", "c")
at_least_one_samp(10, m)

【讨论】:

    猜你喜欢
    • 2013-10-31
    • 2022-01-13
    • 1970-01-01
    • 2015-10-19
    • 2016-12-30
    • 2022-10-08
    • 2021-07-16
    • 2016-09-14
    • 2010-12-28
    相关资源
    最近更新 更多