[R] correlations between columns for each row

Rob Griffin robgriffin247 at hotmail.com
Tue Nov 15 21:14:05 CET 2011

Error in cor(x[a], x[b], use = "complete.obs") : 'x' must be numeric

This is strange, it works on your example (and you've understood what I'm 
trying to do perfectly), but then when I use it on the original data it 
comes up with the error above
I've checked str() and the columns are all numeric


-----Original Message----- 
From: Joshua Wiley
Sent: Tuesday, November 15, 2011 7:14 PM
To: robgriffin247
Cc: r-help at r-project.org
Subject: Re: [R] correlations between columns for each row

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