S Das - 1 year ago 87
R Question

# Order Factored Time Series Data

I have a dataset like the following:

``````a <- read.table(header=TRUE, text="Time Counter Speed
7:55:00    CT08W 63.79
9:30:00    CT08W 67.69
7:05:00    CT11W 68.34
8:40:00    CT10W 68.39
11:00:00    CT11W 68.00
10:40:00    CT01W 21.57
11:35:00    CT02W 72.03
5:25:00    CT12W 66.93
6:10:00    CT02W 62.79
12:05:00    CT02W 71.79                   ")
a
Time Counter Speed
1   7:55:00   CT08W 63.79
2   9:30:00   CT08W 67.69
3   7:05:00   CT11W 68.34
4   8:40:00   CT10W 68.39
5  11:00:00   CT11W 68.00
6  10:40:00   CT01W 21.57
7  11:35:00   CT02W 72.03
8   5:25:00   CT12W 66.93
9   6:10:00   CT02W 62.79
10 12:05:00   CT02W 71.79

str(a)
'data.frame':   10 obs. of  3 variables:
\$ Time   : Factor w/ 10 levels "10:40:00","11:00:00",..: 8 10 7 9 2 1 3 5 6 4
\$ Counter: Factor w/ 6 levels "CT01W","CT02W",..: 3 3 5 4 5 1 2 6 2 2
\$ Speed  : num  63.8 67.7 68.3 68.4 68 ...
``````

I don't want to use
`as.POSIXct`
in the solution as it involves difficulties while annotating the figure.

``````ggplot(a, aes(x=Time, y=Counter, fill=Speed))
``````

The plot shows that time is ordered wrongly. Is there a way to order the time while it is factored?

You can use the a date-time format for your time variable to order your factor.

The key is using the date-time variable to do the sorting, which can be done a variety of ways. Here, I create a date-time variable and sort it when making the factor variable.

``````a\$dt = as.POSIXct(a\$Time, format = "%H:%M:%S")

a\$Time2 = factor(format(a\$dt, "%H:%M:%S"), levels = format(sort(a\$dt), "%H:%M:%S"))
a\$Time2
[1] 07:55:00 09:30:00 07:05:00 08:40:00 11:00:00 10:40:00 11:35:00 05:25:00 06:10:00 12:05:00
Levels: 05:25:00 06:10:00 07:05:00 07:55:00 08:40:00 09:30:00 10:40:00 11:00:00 11:35:00 12:05:00

ggplot(a, aes(x=Time2, y=Counter, fill=Speed))
``````

If using this method and the times aren't unique, you'll need to add `unique` into the `levels` argument.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download