この質問で説明されている同様の問題があります。その質問と同様に、3 つの列 (id、group、value) を持つデータ フレームがあります。各グループから n 個のサンプルを置換して取得し、各グループから n 個のサンプルを含む小さなデータ フレームを生成したいと考えています。
ただし、シミュレーション コードで数百のサブサンプルを実行していますが、ddply に基づくソリューションをコードで使用するには非常に時間がかかります。単純なコードを書き直して、パフォーマンスを向上できるかどうかを確認しようとしましたが、それでもまだ遅いです (ddply ソリューションより悪くはないにしても、良くはありません)。以下は私のコードです。パフォーマンスのために改善できるかどうか疑問に思っています
#Producing example DataFrame
dfsize <- 10
groupsize <- 7
test.frame.1 <- data.frame(id = 1:dfsize, group = rep(1:groupsize,each = ceiling(dfsize/groupsize))[1:dfsize], junkdata = sample(1:10000, size =dfsize))
#Main function for subsampling
sample.from.group<- function(df, dfgroup, size, replace){
outputsize <- 1
newdf <-df # assuming a sample cannot be larger than the original
uniquegroups <- unique(dfgroup)
for (uniquegroup in uniquegroups){
dataforgroup <- which(dfgroup==uniquegroup)
mysubsample <- df[sample(dataforgroup, size, replace),]
sizeofsample <- nrow(mysubsample)
newdf[outputsize:(outputsize+sizeofsample-1), ] <- mysubsample
outputsize <- outputsize + sizeofsample
}
return(newdf[1:(outputsize-1),])
}
#Using the function
sample.from.group(test.frame.1, test.frame.1$group, 100, replace = TRUE)