我有一个问题,我有k项,比方说{0,1},我必须列举所有可能的N抽奖,比方说N=3.也就是说,我试图从矢量中找到给定大小的所有可能样本,并进行替换.
我可以通过以下循环方法到达那里:
for (i1 in c(0,1)){
for (i2 in c(0,1)){
for (i3 in c(0,1)){
print(paste(i1,i2i3,collapse="_"))
}}}
Run Code Online (Sandbox Code Playgroud)
然而,这感觉像一个kludge.使用基础R有更好的方法吗?
你可以使用interaction:
items <- c(0, 1)
n <- 3
levels(interaction(rep(list(items), n), sep = "_"))
# [1] "0_0_0" "1_0_0" "0_1_0" "1_1_0" "0_0_1" "1_0_1" "0_1_1" "1_1_1"
Run Code Online (Sandbox Code Playgroud)