Search code examples
rsortingbar-chartreversecbind

R: Keeping only part of a list & is it possible to reverse cbind?


I have two lists of 37 items each (I put 3 here as an example):

vacancy.locations <- c("Amsterdam", "Zuid Holland", "Utrecht")
count.locations <- c("11", "9", "40")

I binded these two lists together locations <- cbind(vacancy.locations, count.locations so that I could sort in descending order sortedlocations <- locations[order(-count.locations),] and not lose the fact that 11 belonged to Amsterdam and 40 to Utrecht. However, now I want to only keep the 10 locations with the highest count. Can anyone help me do that? After this I want to plot the top 10 locations in a barplot. Currently I'm trying that with the sortedlocations, however I only get 1 bar in the chart with all locations combined.

barplotLocations <- barplot(height=sortedlocations, las=2, main="locations in vacancies", xlab="locations", ylab="number", cex.axis = .5, cex.names = .75)

Help? :)


Solution

  • Here it is an easy way of doing it with ggplot2

    vacancy.locations <- letters
    count.locations <- sample(1:1000, length(letters))
    
    location = cbind.data.frame(vacancy.locations,count.locations)
    location_sorted =  location[order(-count.locations),]
    
    top_location = location_sorted[1:10,]
    top_location[,1] = factor(top_location[,1], levels = top_location[,1][order(top_location[,2])])
    library(ggplot2)
    ggplot(data=top_location, aes(x=vacancy.locations, y=as.factor(count.locations))) +
      geom_bar(stat="identity")