M. Elliott
M. Elliott

Reputation: 129

Sort a dataframe in R using a list that is not numeric or alphabetic, but is ordered

I have a list of weeks of the year that are ordered by the academic calendar that I want to order a data frame by.

weeks <- c("Sept W1", "Sep W2", "Sep W3", "Sept W4",
        "Oct W1", "Oct W2", "Oct W3", "Oct W4",
        "Nov W1", "Nov W2", "Nov W3", "Nov W4")

My data currently looks like the following, and I want to plot it demonstrating change in my week sum over the year, beginning with September, not April.

> newDat %>% group_by(week) %>% summarise(sum_all = sum(week_sum))
Source: local data frame [48 x 2]

       week sum_all
      (chr)   (dbl)
1  April W1   46840
2  April W2   52729
3  April W3   51285
4  April W4   51241
5    Aug W1   12089

As you can see, I'm using dplyr, but maybe there's an easier way to do this with a base function? Thanks.

Upvotes: 0

Views: 33

Answers (1)

Joe
Joe

Reputation: 63424

If you create week as an ordered factor, then the data will be sorted in the order you designate inherently.

weeks <- c("Sep W1", "Sep W2", "Sep W3", "Sep W4",
         "Oct W1", "Oct W2", "Oct W3", "Oct W4",
         "Nov W1", "Nov W2", "Nov W3", "Nov W4")

weekdata <- c("Nov W1" "Nov W1" "Sep W1" "Sep W2" "Oct W1" "Sep W3")

weekdata.f <- factor(weekdata,levels=weeks, ordered=TRUE)

weekdata.order = sort(weekdata.f)

weekdata.order

Upvotes: 4

Related Questions