[R] matrix manipulations

David Andel andel at ifi.unizh.ch
Tue Jul 15 23:27:50 CEST 2003

```Thanks a lot, this does exactly what I was looking for.

On Tue, 15 Jul 2003, Liaw, Andy wrote:

> I don't think for loop is so bad here, but if you insist on not using it,
> try:
>
> > x<-matrix(rnorm(25), 5, 5)
> > sapply(1:5, function(i) cor(x[,i], rowSums(x[,-i])))
> [1] -0.04179336 -0.08613796  0.48194936  0.38317629 -0.22081706
>
> HTH,
> Andy
>
> > -----Original Message-----
> > From: David Andel [mailto:andel at ifi.unizh.ch]
> > Sent: Tuesday, July 15, 2003 12:52 PM
> > To: r-help at stat.math.ethz.ch
> > Subject: [R] matrix manipulations
> >
> >
> > Hi
> >
> > cor(x,apply(x,1,sum)) gives me the correlations of each
> > column with the sums of each row (correct me if I'm wrong, please).
> >
> > What I need are the correlations of each column with the sums
> > of each row except the entry in the given column. It seems
> > that for any one column i I get it by doing:
> >
> > cor(x[,i],apply(x[,-i],1,sum))
> >
> > But I struggle to get it for all the columns. I was trying
> > things like:
> >
> > for(i in 1:ncol(x)) cor(x[,i],apply(x[,-i],1,sum))
> >
> > which doesn't generate any output at all, and
> >
> > > rbind(for(i in 1:ncol(x)) cor(x[,i],apply(x[,-i],1,sum)))
> >           [,1]
> > [1,] 0.1880237
> >
> > outputs just the result of the very last column.
> >
> > I know that it shouldn't be necessary to use for(), but I
> > couldn't figure out a way how to do the task using e.g. apply().
> >
> > How do you get the results of all columns?
> >
> > Thank you,
> > David
> >
> > ______________________________________________
> > R-help at stat.math.ethz.ch mailing list
> > https://www.stat.math.ethz.ch/mailman/listinfo> /r-help
> >

```

More information about the R-help mailing list