# [R] apply & incompatible dimensions error

Benilton Carvalho bcarvalh at jhsph.edu
Tue Jul 24 17:40:14 CEST 2007

```that's garbor's suggestion then.
sorry for the misunderstanding. :-)
b

On Jul 24, 2007, at 11:35 AM, Bernzweig, Bruce ((Consultant)) wrote:

> Thanks Benilton,
>
> I know what I want to do, just not sure how to do it using R.  The
> help
> documentation is not very clear.
>
> What I am trying to do is calculate correlations on a row against row
> basis:  mat1 row1 x mat2 row1, mat1 row1 x mat2 row2, ... mat1 row1 x
> mat2 row-n, mat1 row-n, mat2 row-n
>
> - Bruce
>
> -----Original Message-----
> From: Benilton Carvalho [mailto:bcarvalh at jhsph.edu]
> 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
>
> are you positive that your function is doing what you expect it to do?
>
> it looks like you want something like:
>
> sapply(1:10, function(i) cor(mat1[i,], mat2[i,]))
>
> b
>
> On Jul 24, 2007, at 11:05 AM, Bernzweig, Bruce ((Consultant)) 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
>> guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>
>
>
> **********************************************************************
> Please be aware that, notwithstanding the fact that the person sending
> this communication has an address in Bear Stearns' e-mail system, this
> person is not an employee, agent or representative of Bear Stearns.
> Accordingly, this person has no power or authority to represent, make
> any recommendation, solicitation, offer or statements or disclose
> information on behalf of or in any way bind Bear Stearns or any of its
> affiliates.
> **********************************************************************

```