2

如何更改函数参数名称。例如使用替代我可以更改函数参数值或函数名称:

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))

# 编辑(@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))))
}
4

5 回答 5

4

以类似于实际问题的示例为例,为什么不这样做:

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)。我们不能tagv这里指定,所以只需ll使用单个元素创建列表,"Dunnett"然后在循环中将此列表的名称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)))))
}
于 2012-11-06T16:31:13.887 回答
3

以您的问题标题和第一行的名义,为什么不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
于 2012-11-06T15:13:39.787 回答
2

如果您必须动态更改提供的参数的名称,您可以执行以下操作:

cl <- quote(F(x = a))
names(cl)[names(cl) == "x"] <- "y"
cl
# F(y = a)
于 2012-11-06T15:11:56.967 回答
1

在看到你真正在做的例子之后,你也可以使用parseandsprintf

 print(eval(parse(text=sprintf("summary(glht(fit,linfct= mcp(%s='Dunnett')))",
   v))))
于 2012-11-06T16:16:39.237 回答
1

根据要求,评论移至答案:

我也不会。你真正想做的是什么?通常在 R 中,您可能会foo<- 'G'; bar<-'x' ; do.call(foo,bar)根据字符串对象选择函数及其参数。

于 2012-11-06T16:18:14.953 回答