EDIT:元の質問の後のコメントに基づいて
、あなたは、単に行うことができます。
my.sample <- function(x,n){
samples <- rle(List)$lengths
ng <- length(samples)
groups <- cut(1:ng,n,labels=FALSE)
reps <- tapply(samples,groups,sum)
rep(1:n,reps)
}
> my.sample(List,4)
[1] 1 1 1 1 2 2 3 3 3 3 4 4 4
ベクトルを取得するにはsplit()
で使用できます。
c(1,1,1,1,1,1,1,1,1,2,2,3,3,4,4)のようなベクトルを持つことを開始すると問題が発生します。
- が
- は、n個のグループにそれらを組み合わせたユニークな値のベクトルのリストでベクトルを分割:あなたがシフトする順序を気にしない場合は、次のロジックに基づいて、そのための機能を構築することができます
- グループを超えて、それらの長さがすべて同じかそれより短いかどうかを確認します。そうでない場合は、値の大きいものから小さいものに切り替えます。
- 差が全体の長さのモジュラスおよびグループの数よりも少ない、またはあなたは、アルゴリズムを実行するまで続行10倍(一部の極端な場合にあなたがループしながら、無限に終わる可能性)
を言います
これは、このようなとして適用することができ、以下の機能
my.sample <- function(x,n){
# these are the unique values from which to sample
samples <- split(x,x)
ns <- length(samples)
groups <- list()
# make sure that sample() returns n groups
while(length(groups)!=n){
groups <- split(samples,sample(1:n,ns,replace =TRUE))
}
count <- 0
lgroups <- c(1,ns)
while(diff(range(lgroups)) > ns%%n & count < 10){
lgroups <- sapply(groups,function(i)length(unlist(i))) # length of groups
ngroups <- sapply(groups,length) # number of unique values
id <- which(ngroups > 1) # which groups have more than one unique value
#switch one value from the largest to the smallest group
gmin <- which.min(lgroups)
gmax <- id[which.max(lgroups[id])]
gsw <- sample(1:length(groups[gmax]),1)
groups[[gmin]] <- c(groups[[gmin]],groups[[gmax]][gsw])
groups[[gmax]] <- groups[[gmax]][-gsw]
count <- count+1
}
# create the output
lapply(groups,unlist,use.names=FALSE)
}
を与える:
> my.sample(List,4)
$`1`
[1] 5 5 5 5
$`2`
[1] 11 11 2
$`3`
[1] 3 3 9
$`4`
[1] 1 1 1
それはまだあなた自身のニーズに微調整されることができ、これはRのようなやり方です。
リストに基づいてリストを分割しますか?シーケンス?もしそうなら、 'rle()'を試してください。どのサブリストに入るかを判断する基準は何ですか(サブリストに複数の値がある場合など)。 –
サブリストには値が8つあり、サブリストが4つある可能性があるため、複数の値を持つことができます。各値は1つのサブリストにのみ属していなければなりません。 –
あなたの目的について少し話していただけますか?つまり、あなたが4つに壊れた後にベクターで何をするつもりですか?彼らはカテゴリ変数か連続変数ですか? –