[R] why change days of the week from a factor to an ordered factor?
peter dalgaard
pdalgd at gmail.com
Mon Dec 2 18:37:50 CET 2013
On 02 Dec 2013, at 16:35 , Bert Gunter <gunter.berton at gene.com> wrote:
> Not true, Rich.
>
>> z <-factor(letters[1:3],lev=letters[3:1])
>> sort(z)
> [1] c b a
> Levels: c b a
>
> What you say is true only for the **default** sort order.
>
> (Although maybe the code author didn't realize this either)
The coding is certainly clunky (the phrase about writing FORTRAN in any language springs to mind, only with SAS instead of FORTRAN):
>>>
>>> dodgers$ordered_day_of_week <- with(data=dodgers,
>>> ifelse ((day_of_week == "Monday"),1,
>>> ifelse ((day_of_week == "Tuesday"),2,
>>> ifelse ((day_of_week == "Wednesday"),3,
>>> ifelse ((day_of_week == "Thursday"),4,
>>> ifelse ((day_of_week == "Friday"),5,
>>> ifelse ((day_of_week == "Saturday"),6,7)))))))
>>> dodgers$ordered_day_of_week <- factor(dodgers$ordered_day_of_week,
>>> levels=1:7,
>>> labels=c("Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun"))
>>>
This'll do:
dodgers$ordered_day_of_week <- factor(dodgers$ordered_day_of_week,
levels=c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"),
labels=c("Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun"))
And BTW, it doesn't (and didn't) create an ordered factor, just a factor with a different level ordering.
--
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk Priv: PDalgd at gmail.com
More information about the R-help
mailing list