如何使用字符作为函数的属性 [英] How to use a character as attribute of a function

查看:83
本文介绍了如何使用字符作为函数的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为模型的不同变量运行多重比较分析。我的想法如下:

  library(multcomp)
set.seed(123)
x1< ; - gl(4,1​​0)
x2 <-gl(5,2,40)
y < - rnorm(40)

fm1 <-lm 〜x1 + x2)

for(var in c('x1','x2'))
{
mc1 < - glht(fm1,linfct = mcp ='Tukey'))
print(summary(mc1))
}



错误en mcp2matrix(model,linfct = linfct):
变量'var'在'linfct'中指定,但不能在'model'中找到!



也就是说,不可能使用字符来指定mcp函数。
任何人都知道一个解决方案?

解决方案

更新:确保看到Hadley的答案为了更好的做法,没有诉诸字符串粘贴。我的答案将仍然有用的解释为什么这是比平常更难在这种情况下)。



mcp()的特殊性要求您使用相对粗暴的方法将要评估的表达式粘贴在一起,然后传递它通过 eval(parse())



棘手的是, mcp()以非标准的方式解释其第一个参数。 mcp() x1 ='Tukey' )表示为 x1 赋值'Tukey'相反,整个事物被解释为对预期对比的符号描述。 (在这里,它更像是比较熟悉的公式对象,例如你的 lm() y〜x1 + x2 > call)。

  for(var in c('x1','x2')){
#一个带有您在命令
#行输入的表达式的字符串。例如:mcp(x1 ='Tukey')
exprString < - paste(mcp(,var,='Tukey'))
#eval以获取mcp对象。
LINFCT< - eval(parse(text = exprString))
mc1 < - glht(fm1,linfct = LINFCT)
print(summary(mc1))
}


I want to run a multiple comparisons analysis for the different variables of a model. My idea is as follows:

library(multcomp)
set.seed(123)
x1 <- gl(4,10)
x2 <- gl(5,2,40)
y <- rnorm(40)

fm1 <- lm(y ~ x1 + x2)

for(var in c('x1', 'x2'))
{
mc1 <- glht(fm1, linfct=mcp(var='Tukey'))
print(summary(mc1))
}

When I run, I get the following error:

Error en mcp2matrix(model, linfct = linfct) : 
    Variable(s) ‘var’ have been specified in ‘linfct’ but cannot be found in ‘model’! 

That is, it is not possible to use a character to specify an attribute of the mcp function. Anyone knows a solution?

解决方案

(Update: Make sure to see Hadley's answer for the better way of doing this, without resorting to string-pasting. My answer will still be useful for explaining why that is harder-than-usual in this case.)

The peculiarities of mcp() require you to use the relatively brute force approach of pasting together the expression you'd like to evaluate and then passing it through eval(parse()).

The tricky bit is that mcp() interprets its first argument in a nonstandard way. Within mcp(), x1 = 'Tukey' does not (as it normally would) mean "assign a value of 'Tukey' to the argument x1". Instead, the whole thing is interpreted as a symbolic description of the intended contrasts. (In this, it is much like more familiar formula objects such as the y ~ x1 + x2 in your lm() call).

for(var in c('x1', 'x2')) {
    # Construct a character string with the expression you'd type at the command 
    # line. For example : "mcp(x1 = 'Tukey')"
    exprString <- paste("mcp(", var, "='Tukey')")
    # eval(parse()) it to get an 'mcp' object.
    LINFCT <- eval(parse(text = exprString))
    mc1 <- glht(fm1, linfct = LINFCT)
    print(summary(mc1))
}

这篇关于如何使用字符作为函数的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆