get(paste0(...))覆盖R子阵列中的结果

时间:2017-10-11 14:15:54

标签: r

我有两个子阵列,并希望随机抽样其中一个。子阵列由来自更大标签池的字符标签组成,如下所示:

K <- as.character(1:10)

假设我调用数组K1和K2并在它们之间分配10个标签,如下所示:

K1 <- 1:8
K2 <- 9:10

然后我用

get(paste0("K", i)) 

检索使用&#39; for&#39;进行采样的标签。循环。

我遇到的问题是:如果K1被采样,get(paste0(&#34; K&#34;,i))从K2返回标签(包含标签9:10),而不是根据需要返回K1

换句话说,我相信get(past0(&#34; K&#34;,i))可能会覆盖结果。

有关为何会出现这种情况以及如何绕过这个问题的任何想法?

以下是一个更广泛的例子:

K <- 2
N <- 100
Hstar <- 10
perms <- 10000

probs <- rep(1/Hstar, Hstar)

specs <- 1:N

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

haps <- as.character(1:Hstar)

K1 <- 1:8 # subarray 1
K2 <- 9:10 # subarray 2

for(j in 1:perms){
    for(i in 1:K){ 
        if(i == 1){
            pop[j, specs, i] <- sample(haps, size = N, replace = TRUE, prob = probs)
    }
        else{
            pop[j ,, 1] <- sample(haps[K1], size = N, replace = TRUE, prob = probs[K1])
            pop[j ,, 2] <- sample(haps[K2], size = N, replace = TRUE, prob = probs[K1]) 
        }
    }
}

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

for(k in specs){
    for(j in 1:perms){
        for(i in 1:K){ 
            ind.index <- sample(specs, size = k, replace = FALSE)
            hap.plot <- pop[sample(1:nrow(pop), size = 1, replace = TRUE), ind.index, sample(i, size = 1, replace = TRUE)] 
            HAC.mat[j, k, i] <- length(unique(hap.plot))
        }
    }
}


means <- apply(HAC.mat, MARGIN = 2, mean)
lower <- apply(HAC.mat, MARGIN = 2, function(x) quantile(x, 0.025))
upper <- apply(HAC.mat, MARGIN = 2, function(x) quantile(x, 0.975))

d <- data.frame(specs, means, lower, upper)

par(mfrow = c(1, 2))

    if(i == 1){
        plot(specs, means, type = "n", xlab = "Specimens sampled", ylab = "Unique haplotypes",  ylim = c(1, Hstar))
        polygon(x = c(specs, rev(specs)), y = c(lower, rev(upper)), col = "gray")
        lines(specs, means, lwd = 2)
        HAC.bar <- barplot(N*probs, xlab = "Unique haplotypes", ylab = "Specimens sampled", names.arg = 1:Hstar)
}
else if(i > 1){
    plot(specs, means, type = "n", xlab = "Specimens sampled", ylab = "Unique haplotypes", ylim = c(1, Hstar))
    polygon(x = c(specs, rev(specs)), y = c(lower, rev(upper)), col = "gray")
    lines(specs, means, lwd = 2)
    HAC.bar <- barplot(N*probs[get(paste0("K", i))], xlab = "Unique haplotypes", ylab = "Specimens sampled", names.arg = get(paste0("K", i))) ## The issue may lie here
}

非常感谢任何有关可能发生的事情的建议。

0 个答案:

没有答案