【问题标题】:Sampling values not in sequence采样值不按顺序
【发布时间】:2016-09-06 21:47:55
【问题描述】:

是否可以进行采样,使得可以重复采样值(即 A,B,A ),但不能按顺序(A,A,B),或者只返回一个值(A, A,A) 或 (B,B,B)。下面的代码应该总是给我至少两个值,但我不希望返回的值是按顺序排列的。

x<- 3
alphabet <- LETTERS[seq(1:26)]
a <- sample(alphabet, 2, replace = FALSE)
b <- sample(a, x, replace = TRUE, prob=c(0.5,0.5)) #can't replace
print(b)

【问题讨论】:

    标签: r random sample


    【解决方案1】:

    您可以轻松地使用拒绝抽样,只需检查您的抽奖是否可以接受,如果不可以则重新绘制。您可以使用rle 来检查序列的长度:

    a <- sample(letters, 3, replace=TRUE)
    while(any(rle(a)$lengths > 1)) a <- sample(letters, 3, replace=TRUE);
    

    对于size = 3,您可能不必绘制超过一两次;对于更长的序列,您可能需要更复杂的东西。

    【讨论】:

    • 嗨尼尔,我想这不是我想要的。我在下面做了以下方式。如果有更优雅的方法,我将不胜感激。
    【解决方案2】:

    这段代码可以满足我的需要。在这里我会尝试解释一下。

    # sample 2 letters without replacement. 
    # The sample letter will always be different.
    a <- sample(LETTERS, 2, replace = FALSE) 
    
    # sample 3 times randomly. 
    b <- sample(a, 3, replace=TRUE)
    
    # Reject sampling and repeat again if all the sampled values are the same.
    # b %in% b[duplicated(b)]) return duplicated as TRUE, non duplicated as FALSE
    # sort(unique(b %in% b[duplicated(b)])) returns only TRUE if the sample result consists of 1 sampled value. Keep doing that unless returns FALSE in the first position. 
    
    while(sort(unique(b %in% b[duplicated(b)]))[1] == TRUE){
      b <- sample(a, x, replace=TRUE);
    }
    b
    

    【讨论】:

    • 谢谢!我已经把解释写下来了。我希望它是正确的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-12
    • 2017-11-16
    • 1970-01-01
    • 2018-05-06
    • 1970-01-01
    相关资源
    最近更新 更多