[R] Selection by ordered factors
johnmark
johnmark.agosta at gmail.com
Tue Feb 14 06:26:04 CET 2012
What I want to do is create a data.frame column from ranges of dates (e.g.
annual quarters) as an ordered factor, then use this column to select by
ranges of the factor (e.g. all quarters in 2009).
The factors capture the date ranges, instead of having to write elaborate
code to do range selection.
How I do this is with a function "which.quarter" that returns the date-range
ordered factor corresponding to a date, so I can do things like
/my.data[my.data$date.range.factor >= which.quarter(the.start.date),]
/
The problem is in creating the date-range factor column. Applying
"which.quarter()" to the date column returns a factor that is no-longer
ordered. The cheat I used to fix this is to coerce the column class back to
ordered factor, with this code:
/### Creating a quarters factor column from a date column
## !! Why does unlist return a vector of factors, and not ordered factors?
quarters <- function(date.column) {
qtr.column <- unlist(sapply(date.column, which.quarter ))
class(qtr.column) <- c("ordered", "factor" )
qtr.column
}/
Question:
1) Is there a clean way to preserve the factor ordering thru the
"unlist(sapply(..."?
2) Is there an easier way to manipulate ranges using ordered factors?
Appreciatively - john mark agosta
--
View this message in context: http://r.789695.n4.nabble.com/Selection-by-ordered-factors-tp4386203p4386203.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list