data science

Sorting Vectors – R

A very quick reminder to myself on how to take data from a data frame, place them into vectors, then sort them from highest to lowest.

The Data Frame

# list of users and submissions to the repository
> users <- c('Jose','Bambi','Kisha','Koolaidria','Syndee')
> subs <- c(10,45,67,40,3)

# create dataframe
> df <- data.frame('users'=users,'subs'=subs)

The data frame now looks like this

> df
       users subs
1       Jose   10
2      Bambi   45
3      Kisha   67
4 Koolaidria   40
5     Syndee    3

Create Vector

Get all the subs and create a vector for a bar plot.

> v_subs <- df$subs

# is it a vector?
> is.vector(v_subs)
[1] TRUE
# why...yes, yes it is a vector.

# now create the bar plot
> barplot(v_subs)

we should get something like this.


Sort items in the verctor

We want the bar plot to gor from high to low, left to right.

> v_s_subs <- sort(v_subs, decreasing=TRUE)
# we should get
> v_s_subs
[1] 67 45 40 10  3

The default for `decreasing’ is always FALSE, which means that the numbers will always be sorted from lowest to highest – do not want.

If we plot the graph again with the new vector, this is what we get.

# save to png file...
> png('Desktop/sortedBP.png')
> barplot(v_s_subs)


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s