【问题标题】:R routine always samples from last row of array instead of random rowsR例程总是从数组的最后一行而不是随机行中采样
【发布时间】:2017-08-21 15:41:03
【问题描述】:

我一直在调试以下例程。

引起我注意的一个问题是,每次运行模拟时,总是在数组的最后一行进行采样。我希望它在每次运行代码时随机选择行。

这是我所拥有的:

N <- 10 

Hstar <- 5  

perms <- 10 ### How many permutations are we considering

specs <- 1:N 

设置一个容器来保存每个排列中每个人的身份

pop <- array(dim = c(perms, N))

haps <- as.character(1:Hstar)

分配概率

probs <- rep(1/Hstar, Hstar) 

生成排列

for(i in 1:perms){
    pop[i, ] <- sample(haps, size = N, replace = TRUE, prob = probs)
}

制作一个矩阵来保存每个排列中的 1:N 个个体

HAC.mat <- array(dim = c(perms, N))

for(j in specs){
    for(i in 1:perms){
        ind.index <- sample(specs, size = j, replace = FALSE) ## which individuals will we sample
        hap.plot <- pop[i, ind.index]   ## pull those individuals from a permutation
        HAC.mat[i, j] <- length(unique(hap.plot))  ## how many haplotypes did we get for a given sampling intensity (j) from each ### permutation (i)
    }
}

当我查看 ind.index 和 hap.plot 时,我注意到来自 haps 的值总是取自 pop 变量的最后一行,我很能理解为什么会发生这种情况。我希望它从 pop 中的给定行中随机抽样。

非常感谢任何帮助。

【问题讨论】:

    标签: arrays r


    【解决方案1】:

    我找到了一个看起来可行的解决方法。

    hap.plot <- pop[sample(nrow(pop), size = 1, replace = TRUE), ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-05
      • 1970-01-01
      • 1970-01-01
      • 2017-06-01
      • 2022-01-15
      • 2018-06-11
      • 2012-08-09
      相关资源
      最近更新 更多