how to arrange a table of a variable in ascending order in R and draw a bar-chart

2.9k Views Asked by At

I have created a table from my dataframe(no.out) using only 1 variable(DX_2_CD).

> counts <- table(no.out$DX_2_CD)
> counts

             Blood CirculatorySystems         Congenital          Digestive      Genitourinary 
                 7                133                  0                  7                 35 
        Illdefined           Immunity         Infectious             Injury             Mental 
               126                 98                  0                 84                  7 
          Muscular          Neoplasms            Nervous          Perinatal          Pregnancy 
               119                  7                  0                  0                  7 
       Respiratory              Sense               Skin 
                63                 35                 63 

Now, I want to re-arrange counts in ascending order, such that the lowest value is first and the highest value is the last. If there are two values which are the same, it does not matter which comes first.

2

There are 2 best solutions below

2
On

I think the simplest solution is using order():

ordered_counts <- counts[order(counts)]

or, even better, sort():

ordered_counts <- sort(counts)
2
On

Ok, Now I have managed to get the bars with different colours, using :

    x<-barplot(sort(counts),col=rainbow(length(sort(counts))))#, main="DX_2_CD Distribution", 
           lablist <- as.vector(names(sort(counts)))      
text(cex=1, x=x-.50, y=-1.25, lablist, xpd=TRUE, srt=45)

This solves both the problem.

BUT, the original x-axis labels also remains in addition to the 45 degree slanted labels. How do I get rid of them?

I am not being able to attach the screen-shot since I do not have enough reputation