簡體   English   中英

我可以在后續的函數調用中評估參數嗎?

[英]Can I evaluate an argument in a subsequent function call?

當我嘗試捕獲的值可能在母函數內部更改時,是否可以在后續函數調用中多次評估函數參數?

我遇到的問題與以下示例類似。 我在for循環中有一個母函數f1()和一個rnorm() rnorm(n = ii)應該在循環的每次迭代中接收一個不同的參數(即rnorm(n = ii) ,但是我想在母函數的級別進行控制。

f1 <- function(I, n = 1) {

    res <- vector("list", length = I)

    for (ii in seq_len(I)) {
        res[[ii]] <- rnorm(n = n)
    }
    return(res)
}

f1(I = 2, n = 1)
f1(I = 2, n = ii) # desired, but obviously doesn't work

我試圖玩eval()quote()get()等,但無濟於事。

您需要非標准評估,這意味着您需要在評估函數之前根據函數參數(通常使用substitute )來修改表達式。

f1 <- function(I, n = 1) {

  nval <- substitute(n)


  res <- vector("list", length = I)

  if (is.numeric(nval)) {
    for (ii in seq_len(I)) {
      res[[ii]] <- rnorm(n = n)
    }
  } 

  if (is.name(nval)) {
    for (ii in seq_len(I)) {
      res[[ii]] <- eval(substitute(rnorm(n = nval), list(nval = nval)))
    }
  }

  return(res)
}

f1(I = 2, n = 1)
#[[1]]
#[1] 0.4600974
#
#[[2]]
#[1] -0.6399949

f1(I = 2, n = ii)
#[[1]]
#[1] 0.4554501
#
#[[2]]
#[1] 0.7048373 1.0351035

我認為您的例子只是糟糕的軟件設計。 我強烈建議您不要這樣做。

更好的方法是:

f1 <- function(I, n) {

  res <- vector("list", length = I)

  if (missing(n)) {
    for (ii in seq_len(I)) {
      res[[ii]] <- rnorm(n = ii)
    }
  } else {
    for (ii in seq_len(I)) {
      res[[ii]] <- rnorm(n = n)
    }
  }

  return(res)
}

f1(I = 2, n = 1)
f1(I = 2)

暫無
暫無

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

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