[英]How to create a loop to repeat random sampling procedure in R
我在R中編寫了一些代碼,無需替換3個獨立的向量(list1,list2,list3)。 我從list1中抽樣10次,從列表2中抽樣20次,從列表3中抽樣30次。然后我將3個隨機抽樣列表組合起來,並檢查我對相同字符串抽樣了多少次2或3次。 我如何進行自動化,以便我可以100次采樣並獲得頻率計數分布? 例如,我想看看我從三個列表中隨機抽樣相同字符串的頻率。 謝謝您的幫助。
所有輸入數據都是數千個字符串的列表,如下所示:
列表1:
V1
[1,] "EDA"
[2,] "MGN2"
[3,] "5RSK"
[4,] "NBLN"
我目前的代碼:
sample_list1 <-(sample(list1,10, replace=FALSE))
sample_list2 <-(sample(list2,20, replace=FALSE))
sample_list3 <-(sample(list3,20, replace=FALSE))
combined_randomgenes <- c(list1, list2, list3)
combined_counts <- as.data.frame(table(combined_randomgenes))
overlap_3_lists <- nrow(subset(combined_counts, Freq == 3))
overlap_2_lists <- nrow(subset(combined_counts, Freq == 2))
如果我的3個隨機樣本中只有1個字符串出現在所有3個隨機樣本中,那么我希望overlap_3_lists包含值1.我想自動化,以便我得到值的分布,以便我可以繪制直方圖到查看在所有3個列表中采樣的0,1,2,3等相同字符串的次數。
您也可以嘗試使用mapply()
,稍微更具可讀性,如下所示:
my_list <- list( A= 1:8, B= 1:8, C= 1:8)
my_list_sampled <- mapply(sample, size = c(5,5,3), my_list )
names(my_list_sampled) <- names(my_list)
result<- table(stack(my_list_sampled))
hist(result)
這將很好地總結數據,您可以根據觀察的數量進行分組。
result_all_3 <- (result == "3")
或者像這樣計算重疊
result <- data.frame(ifelse(result> 0, 1, 0))
result$overlap <- rowSums(result)
hist(result$overlap)
您需要在第三個樣本中更改20到30。 另外,你的combined_randomgenes需要引用sample_listx。 然后只需將for循環代碼放在它周圍並分配結果。 額外提示:警惕在腳本中使用subset
並設置種子,以便您的工作可重現。
set.seed(1234)
list1 <- 1:60
list2 <- 1:60
list3 <- 1:60
n <- 100
runs <- data.frame(run=1:n,threes=NA,twos=NA)
for(i in 1:n) {
sample_list1 <-(sample(list1,10, replace=FALSE))
sample_list2 <-(sample(list2,20, replace=FALSE))
sample_list3 <-(sample(list3,30, replace=FALSE))
combined_randomgenes <- c(sample_list1, sample_list2, sample_list3)
combined_counts <- as.data.frame(table(combined_randomgenes))
runs$threes[i] <- sum(combined_counts$Freq==3)
runs$twos[i] <- sum(combined_counts$Freq==2)
}
runs
hist(runs$threes,5)
hist(runs$twos,5)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.