【问题标题】:Substitute results to an error with cor.test用 cor.test 将结果替换为错误
【发布时间】:2017-06-07 20:10:27
【问题描述】:

我正在尝试编写一个循环,它返回线性回归和相关参数。尝试通过 cor.test 函数传递替换时,遇到意外错误

data(iris)
i <- 1
vars <- list(par = as.name(colnames(iris)[1]), expl = as.name(colnames(iris)[2:4][i]))
lm(substitute(par ~ expl, vars), data = iris) # works
lm(Sepal.Length ~ Sepal.Width, data = iris) # works. Result equal to the statement above

cor.test(~Sepal.Length + Sepal.Width, data = iris) # works
cor.test(substitute(~par + expl, vars), data = iris) # does not work
## Error in cor.test.default(substitute(~par + expl, vars), data = iris) :  
## argument "y" is missing, with no default

据我了解,cor.test 语句应该与手动输入的语句相同。

错误的原因是什么?如何为cor.test 编写一个有效的替代语句?

【问题讨论】:

    标签: r correlation


    【解决方案1】:

    错误源于第一个版本是formula类型,第二个是language

    str(substitute(~par + expl, vars))
    # language ~Sepal.Length + Sepal.Width
    str(~Sepal.Length + Sepal.Width)
    # Class 'formula'  language ~Sepal.Length + Sepal.Width
    # ..- attr(*, ".Environment")=<environment: R_GlobalEnv> 
    

    如果你在第二个版本上使用as.formula,它可以工作:

    cor.test(as.formula(substitute(~par + expl, vars)), data = iris)
    # Pearson's product-moment correlation
    # 
    # data:  Sepal.Length and Sepal.Width
    # t = -1.4403, df = 148, p-value = 0.1519
    # alternative hypothesis: true correlation is not equal to 0
    # 95 percent confidence interval:
    # -0.27269325  0.04351158
    # sample estimates:
    # cor 
    # -0.1175698 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-25
      • 1970-01-01
      • 2019-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-18
      相关资源
      最近更新 更多