简体   繁体   中英

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:

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

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.

The code (without the running() command):

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!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM