[英]R - How to get the value of a variable to be treated as a constant?
在R中,定義函數時如何將變量的值用作常量?
在一個循環中,我想做類似的事情:
theta <- vector[n]
f <- function(x)
{
v <- theta * x
return(v)
}
但是我需要稍后能夠重新定義theta,而不必對此功能的定義進行更改? 我已經研究過get(),但這遇到了同樣的問題。
您可以嘗試如下操作:
f <- function(theta) {
t <- theta
function(x) t * x
}
theta <- 5
g <- f(theta)
# g is now a function that multiplies its argument by 5
g(2)
#[1] 10
# Now try to modify theta in the global environment
theta <- 6
# g doesn't change
g(2)
#[1] 10
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.