【问题标题】:How to create a loop to repeat random sampling procedure in R如何创建循环以在 R 中重复随机抽样过程
【发布时间】:2016-08-24 15:35:30
【问题描述】:

我已经在 R 中编写了一些代码来从 3 个单独的向量(list1、list2、list3)中进行采样而不用替换。我从列表 1 中采样 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 等相同的字符串。

【问题讨论】:

    标签: r loops sampling resampling


    【解决方案1】:

    您也可以尝试使用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)
    

    【讨论】:

      【解决方案2】:

      您需要在第三个示例中将 20 更改为 30。此外,您的 combine_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)
      

      【讨论】:

        猜你喜欢
        • 2019-02-20
        • 1970-01-01
        • 2012-08-21
        • 1970-01-01
        • 2018-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多