更改函数参数名称

时间:2012-11-06 14:29:36

标签: r

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

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

5 个答案:

答案 0 :(得分: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)形式的列表。我们无法在此处将tag指定为v,因此只需使用单个元素ll创建列表"Dunnett",然后更改名称属性循环中的此列表为v。然后使用do.call()安排使用此参数列表调用mcp()

为了完整起见,正如@Josh在上面的评论中提到的那样,从@Hadley的这个answer可以使用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)))))
}

答案 1 :(得分: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

答案 2 :(得分:2)

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

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

答案 3 :(得分:1)

在看到您正在做的事情的示例后,您还可以使用parsesprintf

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

答案 4 :(得分:1)

根据要求,评论转到答案:

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