[R] How to merge two functions into one?

Jonsson amen.alyaari at Bordeaux.inra.fr
Fri Feb 22 16:04:53 CET 2013


I am using the code below to calculate the correlation map between two
datasets. This code worked fine.

    dir1 <- list.files("D:thly", "*.bin", full.names = TRUE)
    dir2 <- list.files("D:002", "*.envi", full.names = TRUE)
    file_tot <- array(dim = c(1440, 720, 11, 2))
    for(i in 1:length(dir1)) {
        file_tot[, , i, 1] <- readBin(dir1[i], numeric(), size = 4, 
                                        n = 1440 * 720, signed = T)
        file_tot[, , i, 2] <- readBin(dir2[i], numeric(), size = 4, 
                                        n = 1440 * 720, signed = T)
    }
    resultscor<-apply(file_tot,c(1,2),function(x){cor(x[,1],x[,2],use =
"na.or.complete")})

I would like to calculate the correlation only when the `P-value is lower
than 0.05`. so this function bellow will do the job:

     return_cor = function(x, y)  {
        z = cor.test(x,y)
        if(z[[3]] < 0.05) {
        return(z[[5]])
          } else { 
        return(NA) 
        }
        }

However I got this error(as some pairs of my data are less then 3):

                 Error in cor.test.default(x, y) : not enough finite
observations

in order to avoid this error and return NA when there are less than 3
pairs,this function does the job:

          cor_withN <- function(...) {
          res <- try(cor.test(...)$estimate, silent=TRUE)
          ifelse(class(res)=="try-error", NA, res)
           }
Both functions worked perfectly.How can we merge both functions into one
function so we calculate correlation when P value is (certain value,
threshold) and also do the calculations even if there are less than 3 pairs.




--
View this message in context: http://r.789695.n4.nabble.com/How-to-merge-two-functions-into-one-tp4659365.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list