簡體   English   中英

更改函數參數名稱

[英]change function argument name

如何更改函數參數名稱。 例如使用替換我可以更改函數參數值或函數名稱:

substitute(quote(F(x= A)), list(A= quote(B), F= quote(G)))
## result
quote(G(x = B))

但這不起作用:

substitute(quote(F(x= A)), list(x= quote(y)))
## result
quote(F(x = A))

#EDIT(@Joran這里是真實的例子,也許不是那么真實但非常接近我正在做的事情)

library("multcomp")
data("mtcars")

mtcars$gear <- factor(mtcars$gear)
mtcars$cyl <- factor(mtcars$cyl)
xv <- c("gear","cyl")

for(v in xv){
 fo <- as.formula(paste("mpg",v,sep="~"))
 fit <- lm(fo,data=mtcars)
 print(eval(substitute(summary(glht(fit,linfct= mcp(vn="Dunnett"))),list(vn=v))))
}

以你的實際問題為例,為什么不這樣做:

library("multcomp")
data("mtcars")

mtcars$gear <- factor(mtcars$gear)
mtcars$cyl <- factor(mtcars$cyl)
xv <- c("gear","cyl")

ll <- list("Dunnett")
for(v in xv){
  fo <- as.formula(paste("mpg",v,sep="~"))
  fit <- lm(fo,data=mtcars)
  names(ll) <- v
  print(summary(glht(fit, linfct = do.call(mcp, ll))))
}

這使:

     Simultaneous Tests for General Linear Hypotheses

Multiple Comparisons of Means: Dunnett Contrasts


Fit: lm(formula = fo, data = mtcars)

Linear Hypotheses:
           Estimate Std. Error t value Pr(>|t|)    
4 - 3 == 0    8.427      1.823   4.621 0.000144 ***
5 - 3 == 0    5.273      2.431   2.169 0.072493 .  
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 
(Adjusted p values reported -- single-step method)


     Simultaneous Tests for General Linear Hypotheses

Multiple Comparisons of Means: Dunnett Contrasts


Fit: lm(formula = fo, data = mtcars)

Linear Hypotheses:
           Estimate Std. Error t value Pr(>|t|)    
6 - 4 == 0   -6.921      1.558  -4.441 0.000235 ***
8 - 4 == 0  -11.564      1.299  -8.905 1.71e-09 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 
(Adjusted p values reported -- single-step method)

這里的技巧是要注意mcp的第一個參數是...這通常意味着我們可以傳入表單list(tag = value) 我們不能在這里將tag指定為v ,因此只需使用單個元素"Dunnett"創建列表ll ,然后將循環中此列表的names屬性更改為v 然后使用do.call()來安排使用此參數列表調用mcp()

為了完整性,正如@Josh在上面的評論中提到的那樣,從@Hadley的這個答案中可以使用setNames()函數更簡潔地說明列表:

for(v in xv){
  fo <- as.formula(paste("mpg",v,sep="~"))
  fit <- lm(fo,data=mtcars)
  print(summary(glht(fit, linfct = do.call(mcp, setNames(list("Dunnett"), v)))))
}

以問題標題和第一行的面值為什么不復制函數和/或使用formals()取決於函數名稱或參數是否需要更改?

對於第一個:

F <- function(x = A) {}
G <- F
formals(G) <- alist(x = B)

> args(G)
function (x = B) 
NULL

對於第二個

F <- function(x = A) {}
formals(F) <- alist(y = A)

> args(F)
function (y = A) 
NULL

如果必須動態更改提供的參數的名稱,則可以執行以下操作:

cl <- quote(F(x = a))
names(cl)[names(cl) == "x"] <- "y"
cl
# F(y = a)

在看到你正在做的事情的例子后,你也可以使用parsesprintf

 print(eval(parse(text=sprintf("summary(glht(fit,linfct= mcp(%s='Dunnett')))",
   v))))

根據要求,評論轉移到答案:

我也不願意。 你真的想做什么? 通常在R中,你可能會做foo<- 'G'; bar<-'x' ; do.call(foo,bar) foo<- 'G'; bar<-'x' ; do.call(foo,bar) foo<- 'G'; bar<-'x' ; do.call(foo,bar)根據字符串對象選擇函數及其參數。

暫無
暫無

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

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