[R] reorganizing a data frame

Jim Lemon bitwrit at ozemail.com.au
Sat Jul 8 13:42:28 CEST 2000


Jeff Miller wrote:

>...I would like to turn this data frame into a matrix, closedata, that
looks like
this
                        GE         HIT          INTC
01/02/1998     24.667     71.125     36.313
01/05/1998     25.104     72.313     37.250
01/06/1998     24.771     72.563     36.563
01/07/1998     24.979     NA          36.375
01/08/1998     24.750     NA          37.156

I just realized that you wanted a matrix as output - you may have to
make a little change in the following:

reorg<-function(old.df,rowvar,colvar,reorgvar) {
 if(!missing(old.df) &&
  !missing(rowvar) &&
  !missing(colvar) &&
  !missing(reorgvar)) {
  row.var<-levels(old.df[,rowvar])
  col.names<-levels(old.df[,colvar])
  new.df<-

data.frame(row.var,matrix(0,nrow=length(row.var),ncol=length(col.names)))

  for(i in 1:length(col.names)) {
   new.index<-
    match(row.var,subset(old.df[,rowvar],old.df[,colvar] ==
col.names[i]),NA)
   new.df[,i+1]<-ifelse(is.na(new.index),NA,
   subset(old.df[,reorgvar],old.df[,colvar] == col.names[i])[new.index])

  }
  names(new.df)<-c(names(old.df)[rowvar],col.names)
  return(new.df)
 }
 cat("Usage: reorg(old.df, rowvar, colvar, reorgvar)\n")
}

'rowvar' corresponds to 'date' in your example, 'colvar' to 'ticker' and
'reorgvar' to 'close'.  I think this will do the trick, although it's
not very general.

Jim

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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