我试图从包含每个字符中至少一个的固定数量的字符生成随机序列.
例如有合奏
m = letters[1:3]
我想创建一个N = 10个元素的序列,其中至少包含每个m
字符中的一个,如
a
a
a
a
b
c
c
c
c
a
Run Code Online (Sandbox Code Playgroud)
我试过sample(n,N,replace=T)
但是这样也是一个序列
a
a
a
a
a
c
c
c
c
a
Run Code Online (Sandbox Code Playgroud)
可以生成不包含的内容b
.
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"
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)