在多个子阵列之间移动行

时间:2018-01-05 18:20:07

标签: arrays r

我的问题来自我之前提出的问题,但没有包含我自己的代码(我最初应该这样做)。

Moving rows between subarrays

只能部分解决我的困境。但是我采用了下面代码中的方法。

以下是我特定问题的相关代码:

K <- 2  # number of equally-sized (sub)populations
N <- 5 # total number of sampled individuals
Hstar <- 5 # total number of haplotypes
probs <- rep(1/Hstar, Hstar) # haplotype frequencies
m = 0.1 # migration rate between subpopulations
perms <- 10000 # number of permutations

## Set up container(s) to hold the identity of each individual from each permutation ##

num.specs <- ceiling(N / K)

## Create an ID for each haplotype ##

haps <- 1:Hstar

## Assign individuals (N) to each subpopulation (K) ##

specs <- 1:num.specs

## Generate permutations, assume each permutation has N individuals, and sample those individuals' haplotypes from the probabilities ##

gen.perms <- function() {
    sample(haps, size = num.specs, replace = TRUE, prob = probs)
}

pop <- array(dim = c(perms, num.specs, K))

for (i in 1:K) {
    pop[,, i] <- replicate(perms, gen.perms())
}

## Allow individuals from permutations to migrate between subpopulations ##

for (i in 1:K) {
    if (m != 0){
        ind <- sample(perms, size = perms * m, replace = FALSE) # sample random row from random subpopulation
    }
    pop[ind,] ## should swap rows between subarrays, but instead throws an error.
}

&#39; IND&#39;标识要交换的行。

目标是将链接问题中最初询问的行从一个子群体(=子阵列)交换到另一个子群体。例如,用子阵列2的行100切换子阵列1的第1行。最重要的是,我需要保留数组类型。最后,&#39; pop&#39;必须有维度= c(烫发,num.specs,K)。可以这样做吗?

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

我觉得你忘了写一个逗号。我想你需要改变第38行:

pop[ind,,] ## should swap rows between subarrays, but instead throws an error.

如果您想继续使用已更改的pop - 数组,并使用交换行,则需要将其存储在变量中。例如:

pop_new <- pop[ind,,]

或者您可以将其存储在同一个变量中,这意味着它将覆盖pop的旧内容。当您使用相同的向量(ind)作为索引以及目标变量时,只替换旧值。使用sample()随机交换行:

pop[ind,,] <- pop[sample(ind),,]