[英]Returning p value and correlation coefficient from modified cor.test
I am trying to run a modified version of the cor.test, using the following code which I found on another handy thread on stackoverflow: 我正在尝试使用我在stackoverflow上另一个方便线程上找到的以下代码来运行cor.test的修改版本:
cor_withN <- function(...) {
res <- try(cor.test(...)$estimate, silent=TRUE)
ifelse(class(res)=="try-error", NA, res)
}
I am using this with the running() command to perform a bunch of moving window correlations that contain some NAs. 我将此与running()命令一起使用,以执行一堆包含某些NA的移动窗口关联。 I would like to return at least the correlation coefficient and p-value (but if I can get the test statistic and df as well, that would be fantastic).
我想至少返回相关系数和p值(但如果我也能获得测试统计量和df,那将是很棒的)。
I have tried removing the $estimate part, in hopes that it would return everything I mentioned above, but I got a pretty ugly, incomplete output. 我试图删除$ estimate部分,希望它能返回我上面提到的所有内容,但是我得到了一个非常丑陋,不完整的输出。
The code (without the running() command): 代码(没有running()命令):
cor_withN2 <- function(...) {
res <- try(cor.test(...), silent=TRUE)
ifelse(class(res)=="try-error", NA, res)
}
cor_withN2(x, y)
[[1]]
t
1.948752
I would appreciate any suggestions on how this could be modified to return all of the stats that I'm looking for, or another approach to achieving this result. 对于如何修改此方法以返回我正在寻找的所有统计信息的任何建议,或者获得此结果的另一种方法,我将不胜感激。
Thank you! 谢谢!
Welcome to SO! 欢迎来到SO!
I think your problem is that ifelse()
is designed for vectors of conditional expressions as well as of alternative values, while the latter are automatically and intransparently recycled/truncated to agree with the length of the condition (in your case, probably shortened to one, so that only the t-value is returned). 我认为您的问题是
ifelse()
设计用于条件表达式和替代值的向量,而后者会自动且不透明地循环/截断以与条件的长度一致(在您的情况下,可能缩短为一个,以便仅返回t值)。
Consider rephrasing the last statement from your function along the lines of 考虑按照以下方式改写函数中的最后一条语句:
if (class(res)=="try-error") NA else unclass(res)[c("estimate","p.value")]
...(or try to provide an executable example that comes with sample data). ...(或尝试提供示例数据随附的可执行示例)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.