[R] taking rows from a data frame

ripley@stats.ox.ac.uk ripley at stats.ox.ac.uk
Thu Nov 21 08:56:58 CET 2002


Let's be careful.  You cannot in general compute the correlation between
`a row of a data frame and a vector'.  The columns of a data frame can be
of different types, so this is only possible if they are all numeric (or
integer or complex).  It would be better to use a matrix, and that is what
apply does implicitly (as.matrix).  However, it would be safer to do the
conversion yourself and check you get a numeric matrix back.

Contrast data.matrix() and as.matrix() and consider which you want.

If the matrix has many rows there are more efficient ways to do this via
matrix operations.

On Wed, 20 Nov 2002, Bill Oliver wrote:

> Lei Jiang wrote:
> > hi, there.
> >
> > Here is my problem. I have a data frame by read.table(). I want to take
> > every row from this data frame and compute the correlation between the
> > current row and a fixed vector. finally I want to append the correlation
> > computed as a column to the data frame.
> >
> > this is what i am doing.
> > df<-read.delim("filename", col.names=v)
> > myv<-c(....)#this is my vector that I need to compute cor with
> > corv<-cor(t(df[,c(..)]), myv, use="complete.obs") #only use c(..) in df
> >
> > the values I got from corv doesnt seem to be right when I tried to verify
> > them. the way i am doing this is probably not very smart or totally wrong.
> > Can someone help?
>
> Perhaps the following would do the trick.
>
> df$corv <- apply(df,1,function(x) cor(x,myv,use="complete.obs"))
>
> -Bill
>
>
> -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
> r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
> Send "info", "help", or "[un]subscribe"
> (in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
> _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
>

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list