[R] correlations between columns for each row

Joshua Wiley jwiley.psych at gmail.com
Tue Nov 15 19:14:19 CET 2011

Hi Rob,

Here is one approach:

## define a function that does the calculations
## (the covariance of two vectors divided by the square root of
## the products of their variances is just a correlation)
rF <- function(x, a, b) cor(x[a], x[b], use = "complete.obs")

bigdata <- matrix(rnorm(271 * 13890), ncol = 271)

results <- apply(bigdata, 1, FUN = rF, a = 174:213, b = 214:253)

## combine
bigdata <- cbind(bigdata, iecorr = results)

Hope this helps,


On Tue, Nov 15, 2011 at 8:42 AM, robgriffin247
<robgriffin247 at hotmail.com> wrote:
> Just as an update on this problem:
> I have managed to get the variance for the selected columns
> Now all I need is the covariance between these 2 selections -
> the two target columns are and the aim is that a new column contain a
> covariance value between these on each row:
> maindata[,c(174:213)] and maindata[,c(214:253]
> I've played around with all sorts of apply (and derivatives of apply) and in
> various different setups so I think I'm close but I feel like I'm chasing my
> tail here!
> --
> View this message in context: http://r.789695.n4.nabble.com/correlations-between-columns-for-each-row-tp4039193p4073208.html
> Sent from the R help mailing list archive at Nabble.com.
> ______________________________________________
> R-help at r-project.org 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.

Joshua Wiley
Ph.D. Student, Health Psychology
Programmer Analyst II, ATS Statistical Consulting Group
University of California, Los Angeles

More information about the R-help mailing list