使用cor.test

时间:2017-06-07 11:55:22

标签: r correlation

我正在尝试编写一个循环,它返回线性回归和相关参数。当尝试通过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编写替代语句?

1 个答案:

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