[R] cor inside/outside a function has different output

Gabor Grothendieck ggrothendieck at gmail.com
Tue Jul 24 17:47:56 CEST 2007


I think this is really answered already in my previous post but just in case
try this:

> res1 <- t(apply(mat1, 1, cor, t(mat2)))
> res2 <- cor(t(mat1), t(mat2))
> all.equal(res1, res2, check.attributes = FALSE)
[1] TRUE


On 7/24/07, Bernzweig, Bruce (Consultant) <bbernzwe at bear.com> wrote:
> I'm calculating correlations between two matrices
>
>
>
> mat1 <- matrix(sample(1:500,25), ncol = 5,
>
> dimnames=list(paste("mat1row", 1:5, sep=""),
>
> paste("mat1col", 1:5, sep="")))
>
>
>
> mat2 <- matrix(sample(501:1000,25), ncol = 5,
>
> dimnames=list(paste("mat2row", 1:5, sep=""),
>
> paste("mat2col", 1:5, sep="")))
>
>
>
> using what would seem to be two similar methods:
>
>
>
>  Method 1:
>
>
>
>       > f <- function(x,y) cor(x,y)
>
>       > apply(mat1, 1, f, y=mat2)
>
>
>
>  Method 2:
>
>
>
>        > cor(mat1, mat2)
>
>
>
> However, the results (see blow) are different:
>
>
>
> > apply(mat1, 1, f, y=mat2)
>
>
>
>               mat1row1   mat1row2    mat1row3    mat1row4    mat1row5
>
> [1,] -0.27601028 -0.1352143  0.03538690 -0.03084075 -0.60171704
>
> [2,] -0.01595532 -0.3881197 -0.43663982  0.49081806  0.33291995
>
> [3,]  0.35969624 -0.0582948  0.57462169  0.09926796 -0.02948423
>
> [4,] -0.41435920 -0.7164638 -0.21213496 -0.55183934 -0.25341790
>
> [5,]  0.33802803  0.5371508  0.05219095  0.83533575  0.17850291
>
>
>
> > cor(mat1, mat2)
>
>            mat2col1    mat2col2   mat2col3   mat2col4   mat2col5
>
> mat1col1 -0.84077496 -0.01538414 -0.6078933 -0.2263840 -0.1421335
>
> mat1col2  0.23074421  0.54606286 -0.2354733  0.5214255 -0.2129077
>
> mat1col3 -0.80000528  0.19550100 -0.5920509 -0.8694040  0.6853990
>
> mat1col4  0.08050976 -0.55449840  0.6225666  0.6187971 -0.8971584
>
> mat1col5 -0.10199564 -0.43854767 -0.5803077 -0.5100285  0.2848351
>
>
>
> Also, for method 2, the calculations are done on a column x column
> basis.  Is there any way to do this on a row by row basis.  Looking at
> the help page for cor, I don't see any parameters that could be used to
> do this.
>
>
>
> Thanks,
>
>
>
> - Bruce
>
>
>
>
> **********************************************************************
> Please be aware that, notwithstanding the fact that the pers...{{dropped}}
>
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
>



More information about the R-help mailing list