0
votes

I have a small data set like this:

   Wday     av_obs

   Tue       385
   Thu       321
   Fri       440
   Wed       398
   Sat       419
   Mon       312
   Sun       547

Wday is a character variable that indicates the day of a week and av_obs is a numeric variable showing the average number of observations made on that weekday. To plot this relationship I would like to turn the Wday variable into a factor variable with the levels according to a "normal" week. (like this: Mon < Tue < Wed < Thu < Fri < Sat < Sun)

I know about the as.factor function, but I think it doesn't allow me to decide the levels of the factor myself. It just copies the order from the data frame.

If you know a quick and easy approach to this, let me know & thanks in advance!

1
Try: x$Wday <- factor(x$Wday, c("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"))GKi

1 Answers

0
votes

First of all the main difference between factor() and as.factor() is first one offers a series of arguments including to define ordered levels. Here an example with reproducible example:

df <- data.frame(
Wdays = weekdays(seq(as.Date("2021-01-25"),as.Date("2021-01-31"),by='day')),
av_obs = sample(350:600,7),
stringsAsFactors = FALSE
)
df$Wdays_factor <- factor(df$Wdays,levels=df$Wdays,ordered = TRUE) # to levels argument   
different type of order can be written



df$Wdays_factor[1] < df$Wdays_factor[3]