[R] reorganizing a data frame

Brahm, David David.Brahm at fmr.com
Mon Jul 10 18:44:01 CEST 2000


Jeff Miller wants to turn a dataframe (stockdata) containing date, ticker,
and close into a matrix (closedata).  Here's how I'd do it in S-Plus (sorry,
I haven't tried this in R):
 
dates <- sort(unique(stockdata$date))
tickers <- sort(unique(stockdata$ticker))
closedata <- matrix(NA, length(dates), length(tickers),
dimnames=list(as.character(dates), tickers))
idx <- cbind(match(stockdata$date, dates), match(stockdata$ticker, tickers))
closedata[idx] <- stockdata$close
 
The key here is knowing that you can index into a matrix (closedata) with an
Nx2 matrix (idx), each row of which represents one element's coordinates.
This method is especially efficient if your matrix "closedata" is sparse.
 
P.S. The "as.character" is there because S-Plus 5.1 allows for non-character
dimnames, which seems foolish to me, and I use numbers for dates.

-- David Brahm 
    Fidelity Investments 
    (617)563-7438 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: https://stat.ethz.ch/pipermail/r-help/attachments/20000710/e5eada30/attachment.html


More information about the R-help mailing list