3 つのデータ ソースがあります。
types<-c(1,3,3)
places<-list(c(1,2,3),1,c(2,3))
lookup.counts<-as.data.frame(matrix(runif(9,min=0,max=10),nrow=3,ncol=3))
assigned.places<-rep.int(0,length(types))
「タイプ」ベクトルの数字は、特定の観測がどの「タイプ」であるかを教えてくれます。場所リストのベクトルは、観測がどの場所で見つかるかを教えてくれます (一部の観測は 1 か所だけで見つかり、その他はすべての場所で見つかります)。定義により、タイプには 1 つのエントリがあり、観測ごとに場所に 1 つのリストがあります。Lookup.counts は、(別のデータ ソースから生成された) 各場所にある各タイプの観測の数を教えてくれます。
lookup.counts から生成された確率に基づいて、各観測をランダムに場所に割り当てたいと考えています。for ループを使用すると、次のようになります」
for (i in 1:length(types)){
row<-types[i]
columns<-places[[i]]
this.obs<-lookup.counts[row,columns] #the counts of this type in each place
total<-sum(this.obs)
this.obs<-this.obs/total #the share of observations of this type in these places
pick<-runif(1,min=0,max=1)
#the following should really be a 'while' loop, but regardless it needs help
for(j in 1:length(this.obs[])){
if(this.obs[j] > pick){
#pick is less than this county so assign
pick<- 100 #just a way of making sure an observation doesn't get assigned twice
assigned.places[i]<-colnames(lookup.counts)[j]
}else{
#pick is greater, move to the next category
pick<- pick-this.obs[j]
}
}
}
これをどうにかしてベクトル化しようとしましたが、'places' と 'this.obs' の可変長に引っかかっています。
もちろん、実際には、lookup.counts テーブルはかなり大きく (500 x 40)、長さ 1 から長さ 39 の場所リストを含む 900K の観測があります。