[R] apply & incompatible dimensions error
Bernzweig, Bruce (Consultant)
bbernzwe at bear.com
Tue Jul 24 17:33:24 CEST 2007
Thanks Gabor!
You state that my apply is taking rows of mat1 with columns of mat2.
Is this because I have the y=mat2 parameter?
> apply(mat1, 1, f, y=mat2)
Actually, what I would like is to run the correlations on a row against
row basis: mat1 row1 x mat2 row1, etc.
Thanks again,
- Bruce
-----Original Message-----
From: Gabor Grothendieck [mailto:ggrothendieck at gmail.com]
Sent: Tuesday, July 24, 2007 11:31 AM
To: Bernzweig, Bruce (Consultant)
Cc: r-help at stat.math.ethz.ch
Subject: Re: [R] apply & incompatible dimensions error
Your apply is trying to take the correlations of the rows of mat1 with
the
columns of mat2 which, of course, does not work if they have different
numbers of columns. I think you mean to take the correlations of the
columns
of mat1 with the columns of mat2. For example, to take the correlations
of the 5 columns of mat1 with the first 4 columns of mat2 try:
> cor(mat1, mat2[,1:4])
col1 col2 col3 col4
col1 -0.34624254 -0.2669519 -0.2705077 0.2183249
col2 -0.26553255 -0.2687643 -0.0865895 0.1819025
col3 0.19474613 -0.2334986 0.1746522 0.2326915
col4 0.09328338 0.5117784 0.2413143 -0.3374916
col5 0.27519716 0.1605331 -0.4057137 0.3282105
On 7/24/07, Bernzweig, Bruce (Consultant) <bbernzwe at bear.com> wrote:
> Hi,
>
> I've created the following two matrices (mat1 and mat2) and a function
> (f) to calculate the correlations between the two on a row by row
basis.
>
> mat1 <- matrix(sample(1:500,50), ncol = 5,
> dimnames=list(paste("row", 1:10, sep=""),
> paste("col", 1:5, sep="")))
>
> mat2 <- matrix(sample(501:1000,50), ncol = 5,
> dimnames=list(paste("row", 1:10, sep=""),
> paste("col", 1:5, sep="")))
>
> f <- function(x,y) cor(x,y)
>
> When the matrices are squares (# rows = # columns) I have no problems.
>
> However, when they are not (as in the example above with 5 columns and
> 10 rows), I get the following error:
>
> > apply(mat1, 1, f, y=mat2)
> Error in cor(x, y, na.method, method == "kendall") :
> incompatible dimensions
>
> Any help would be appreciated. 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.
>
**********************************************************************
Please be aware that, notwithstanding the fact that the pers...{{dropped}}
More information about the R-help
mailing list