2017-08-25 49 views
1

給定4個數字對象,例如:取樣並允許重複,但不能在連續出現兩次時出現

df<-data.frame(a=1:5, b=6:10, c=11:15, d=16:20) 

如何處理來自這些對象的樣本值,允許重複,而不是連續兩次獲取相同的值?

不正常:

7, 3, 3, 12, 17 (two 3's in a row) 

確定:

17, 3, 7, 2, 7 (duplicates, but no value appears twice in a row) 
+2

做拒收抽樣。 – Roland

回答

1

非常手動,您可以測試每個數是否等於所有其他號碼,並檢驗是否有兩個TRUE的一排,並基於此,重複採樣直到條件爲FALSE

你可以像這樣實現一個功能。

sampler <- function(number_sample) { 
    x <- sample(1:number_sample, replace = TRUE) 
    pre_test <- lapply(x, function(single_number) diff(which(single_number == x)) == 1) 
    test <- any(sapply(pre_test, any)) 

    if (test) sampler(number_sample) else x 
} 

sampler(100) 
sampler(10) 

這很自然地變得很慢,數量很高。

0

基於樣本()的替代函數。

custom.sampling <- function(pool, elems) { 
    # arg check 
    if ((!is.vector(pool))| 
    elems < 2) 
    stop("Bad params") 

    #init and proceed 
    tmp <- c(1,1) 
    while (sum(table(tmp) == 2) >0){ 
    tmp <- sample(pool, size = elems, replace = T) 
    } 
    return(tmp) 
} 

pool <- 0:9 
elems <- 5 
custom.sampling(pool, elems) 
+0

這使用table()來快速檢查並防止重複。 –

0

你可以做這樣的事情......

values <- 1:4 #values to sample from 
len <- 20 #number of samples 
samp <- sample(values,1) #initialise variable 
length(samp) <- len 
sapply(2:len, function(i) samp[i] <<- sample(setdiff(values, samp[i-1]), 1)) 

samp 
[1] 2 1 4 1 4 3 2 4 3 1 3 1 4 3 4 1 3 1 4 2 

<<-運營商改變了samp在全球環境中的值作爲sapply循環的進行,所以每一次樣本values排除先前的值。

相關問題