# [R] cor() on sets of vectors

Bert Gunter gunter.berton at gene.com
Thu Feb 23 23:24:43 CET 2012

```Use 1:n as an index.

e.g.
sapply(1:n, function(i) cor(x[,i],y[,i]))

-- Bert

On Thu, Feb 23, 2012 at 2:10 PM, Sam Steingold <sds at gnu.org> wrote:
> suppose I have two sets of vectors: x1,x2,...,xN and y1,y2,...,yN.
> I want N correlations: cor(x1,y1), cor(x2,y2), ..., cor(xN,yN).
> my sets of vectors are arranged as data frames x & y (vector=column):
>
>  x <- data.frame(a=rnorm(10),b=rnorm(10),c=rnorm(10))
>  y <- data.frame(d=rnorm(10),e=rnorm(10),f=rnorm(10))
>
> cor(x,y) returns a _matrix_ of all pairwise correlations:
>
>  cor(x,y)
>          d          e            f
> a 0.2763696 -0.3523757 -0.373518870
> b 0.5892742 -0.1969161 -0.007159589
> c 0.3094301  0.1111997 -0.094970748
>
> which is _not_ what I want.
>
> I want diag(cor(x,y)) but without the N^2 calculations.
>
> thanks.
>
> --
> Sam Steingold (http://sds.podval.org/) on Ubuntu 11.10 (oneiric) X 11.0.11004000
> http://www.childpsy.net/ http://iris.org.il http://americancensorship.org
> Never argue with an idiot: he has more experience with idiotic arguments.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> and provide commented, minimal, self-contained, reproducible code.

--

Bert Gunter
Genentech Nonclinical Biostatistics

Internal Contact Info:
Phone: 467-7374
Website: