Unable to sort months column chronologically in R

I have a column called Month which is of character type in a dataframe.There are only three values:April,March and May.I have tried converting them to factors and even tried ordering them but they still appear in alphabetical order while using any functions or plots.Can you please help.

1 Like

please show the code you attempted, i.e the factor conversion

unisim_usage_hours_2020$Month<-as.factor(unisim_usage_hours_2020$Month)

unisim_usage_hours_2020$Month<-factor(unisim_usage_hours_2020$Month,levels=month.abb)

the second approach is likely to work if month.abb contains properly ordered matching month levels to that seen in unisim_usage_hours_2020$Month

So what should I do then.Please suggest

you should know what month.abb contains , and whether its correct for unisim_usage_hours_2020$Month.
If you want my opinion, you should tell me what these contain.
Would you like my advice on how to describe to me what they contain ?

They basically convert numeric variables to abbreviations.I have tried using month.name also but it doesn't work.Can you please advise and suggest any or the correct way(s) of sorting the months chronologically.

unisim_usage_hours_2020<- data.frame(Month=c("Feb","Jan"))
month.abb <- c("Jan","Feb")

unisim_usage_hours_2020$Monthf <- factor(x=unisim_usage_hours_2020$Month,
                                         levels=month.abb)

arrange(unisim_usage_hours_2020,Monthf)

So is there any way to do the same without converting it to factor as its still not yielding results.

For additional help , please provide a reprex
FAQ: How to do a minimal reproducible example ( reprex ) for beginners

I was able to do it properly by using levels=month.name and then sorting on it.

I had one more doubt.Now that it's an ordered column,so when I use it in pie chart in the legend section,it throws an error saying that legend is missing,default with no attributes.So the pie chart displays but no legends are shown.

if you provide a reprex, I can offer to debug it for you.

month_count_percent<-round((count_records_per_month$count/sum(count_records_per_month$count))*100,1)

pie(count_records_per_month$count, labels = month_count_percent, main = "2020 Machines per Month pie chart",col = rainbow(length(count_records_per_month$count)))
legend("topright",count_records_per_month$Month, cex = 0.8,
fill = rainbow(length(count_records_per_month$count)))

Error in as.graphicsAnnot(legend) :
argument "legend" is missing, with no default

The syntax for legend is

legend(x, y=NULL, legend, fill, col, bg)

The error message is saying that the third param (legend) is not provided by you

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.