簡體   English   中英

提取局部函數參數以在R中全局使用

[英]Extract local function argument to be used globally in R

我在R中創建了一個具有多個參數的函數。 我希望能夠全局調用這些參數,以在函數外部使用。

如何輕松做到這一點? 我在想,也許match.fun()和match.arg()是這里需要的。 我對此是否正確?

我的功能如下:

HAC.sim <- function(K, N, Hstar, p, probs, perms = 10000){

specs <- 1:N

### Set up a container to hold the identity of each individual from each permutation

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

### Create an ID for each haplotype

haps <- as.character(1:Hstar)

### Assign probabilities of occurrence to each haplotype, ensure they sum to 1
### This is where we assume we "know" the distribution of haplotypes
### Here, I have assumed they all occur with equal frequency, but you can change this to            assume some dominant ones and some rare ones, whatever you want

# probs <- rep(1/Hstar, Hstar) 
probs <- c(0.45, 0.45, rep(0.10/8, 8))

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

# If K > 1, haplotypes are partitioned into equally-sized subpopulations/demes
# Can change number of haplotypes in each subpopulation and re-run simulation 
# For each additional, K, add new Ki and new pop[j ,, i] in loop

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[K2]) 
        }
    }
}

### Make a matrix to hold the 1:N individuals from each permutation

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) ## which individuals will we sample
            hap.plot <- pop[sample(1:nrow(pop), size = 1, replace = TRUE), ind.index, sample(1:K, size          = 1, replace = TRUE)] ## pull those individuals from a permutation
            HAC.mat[j, k, i] <- length(unique(hap.plot))  ## how many haplotypes did we get for a given sampling intensity (k) from each ### permutation (j)
        }
    }
}

### Calculate the mean and CI for number of haplotypes at each sampling intensity (j)

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)

### Plot the curve and frequency barplot

par(mfrow = c(1, 2))

for(i in 1:K){
    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{
        plot(specs, means, type = "n", xlab = "Specimens sampled", ylab = "Unique haplotypes", ylim = c(1, max(HAC.mat)))
        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)))
    }
}

## Measures of Closeness ##

cat("\n Mean number of haplotypes sampled: " , max(means))
cat("\n Mean number of haplotypes not sampled: " , Hstar - max(means))
cat("\n Proportion of haplotypes sampled: " , max(means)/Hstar)
cat("\n Proportion of haplotypes not sampled: " , (Hstar - max(means))/Hstar)

cat("\n")

cat("\n Mean estimate of N*: ", (p*N*Hstar)/max(means))

}

HAC.sim(K = 1, N = 100, Hstar = 10, p = 0.95, probs = probs, perms = 10000)

我希望參數“ p”可用於傳遞給另一個函數。 我應該只在函數中使用省略號(...)來指定其他參數嗎?

如果我正確理解了您的要求,這將演示如何從函數的參數中分配全局環境值。

> ls()
character(0)
> fn <- function(a, b, c) { 
   global_a <<- a
   global_b <<- b
   global_c <<- c
  a*b*c
}
> ls()
[1] "fn"
> fn(2, 3, 4)
[1] 24
> ls()
[1] "fn"       "global_a" "global_b" "global_c"
> global_a
[1] 2

但是,我強烈建議您圍繞要解決的問題找到另一種方法,因為這種方法可能會導致很多麻煩。

如果您僅對某些參數感興趣,則可以將參數作為屬性傳遞給結果:

fn_attr <- function(a, b, c) {
    res <- a * b * c
    attr(res, "args") <- list(a = a, c = c)
    res
}

> foo <- fn_attr(2, 3, 4)
> attr(foo, "args")$a

或獲取所有參數值:

fn_attr_all <- function(a, b, c) {
    args_vals <- as.list(environment())
    res <- a * b * c
    attr(res, "args") <- args_vals
    res
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM