2012-05-04 1 views
2

Using a sample list as a template for sampling from a larger list without wraparoundで私の質問と同様に、ラップアラウンドを許可する方法を知るにはどうすればよいですか?したがってサンプルリストをラップアラウンド付きの大きなリストからサンプリングするためのテンプレートとして使用する

、Iは、文字のベクトルがある場合:

> all <- letters 
> all 
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z" 

を、以下のように、私は文字から参照サンプルを定義:要素間の間隔は、2(1である

> refSample <- c("j","l","m","s") 

ました1〜2番目)、1(2〜3番目)、6(3〜4番目)のいずれかを選択すると、refSampleと同じラップアラウンド間隔を持つallのサンプルをnたとえば、"a","c","d","j","q" "s" "t" "z"および"r" "t" "u" "a"は有効なサンプルですが、"a","c","d","k"は有効ではありません。

この場合も、関数に対してパラメータ化されたものが最適です。

答えて

3

私は運動としてそれを残したが、ここに行くだろう -

all <- letters                                                                 
refSample <- c("j","l","m","s")  

pick_matches <- function(n, ref, full, wrap = FALSE) {                                                       
    iref <- match(ref,full)                                                              
    spaces <- diff(iref)                                                               
    tot_space <- sum(spaces)                                                              
    N <- length(full) - 1                                                              
    max_start <- N - tot_space*(1-wrap)                                                           
    starts <- sample(0:max_start, n, replace = TRUE)                                                        
    return(sapply(starts, function(s) full[ 1 + cumsum(c(s, spaces)) %% (N+1) ]))                                               
}                                                                    


> set.seed(1)                                                                 



> pick_matches(5, refSample, all, wrap = FALSE)                                                        
     [,1] [,2] [,3] [,4] [,5]                                                             
[1,] "e" "g" "j" "p" "d"                                                             
[2,] "g" "i" "l" "r" "f"                                                             
[3,] "h" "j" "m" "s" "g"                                                             
[4,] "n" "p" "s" "y" "m"   

> pick_matches(5, refSample, all, wrap = TRUE)                                                        
     [,1] [,2] [,3] [,4] [,5]                                                             
[1,] "x" "y" "r" "q" "b"                                                             
[2,] "z" "a" "t" "s" "d"                                                             
[3,] "a" "b" "u" "t" "e"                                                             
[4,] "g" "h" "a" "z" "k"   
+0

あなたは剰余演算で間違った何かを持っています。 'mod < - function(x)((x - 1L)%% length(full))+ 1L'を定義して、あなたの' cumsum'の周りにラップすることをお勧めします。 – flodel

+0

+1は両方の答えを同じ関数に折り返します。 – flodel

+0

@flodel - 確かに指摘してくれてありがとう - 私はN + 1の代わりにN-1を持っていました。それを固定した。 –

関連する問題