[R] reorganizing a data frame
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),
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
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the R-help