4

Hi I have made this function that takes a table and prepare the label for a barplot

prepare_labels <- function(ft){
  labs <- ft
  labs <- paste(labs, "\n", sep="")
  labs <- paste(labs, round(prop.table(ft)*100,2), sep="")
  labs <- paste(labs, "%", sep="")
  return(labs)
}

It actually works fine, but is there any better way to write that function, the above code looks ugly and I want to write beautiful code :-)

ex:

ft <- table(mydata$phone_partner_products)
prepare_labels(ft)
[1] "3752\n34.09%" "226\n2.05%"   "2907\n26.41%" "1404\n12.76%" "1653\n15.02%"
[6] "1065\n9.68%" 
rslite
  • 81,705
  • 4
  • 44
  • 47

3 Answers3

6

Since the sep argument is the same for all the paste calls, then you can combine into a single one:

labs <- paste(ft,"\n",round(prop.table(ft)*100,2),"%",sep="")
James
  • 65,548
  • 14
  • 155
  • 193
5

Or, using ggplot2:

ggplot(mtcars, aes(factor(cyl))) + geom_bar() + stat_bin(aes(label = paste(prop.table(..count..) * 100, "%", sep = "")), vjust = -0.2, geom = "text", position = "identity")

and get something like this:

alt text http://img532.imageshack.us/img532/8201/barplotwpct.png

aL3xa
  • 35,415
  • 18
  • 79
  • 112
  • This is quite Nice! Do you know how to reorder the columns with ggplot. I have 5 levels but they are displayed in the wrong order. "dont_know", "maybe_interesting", "not_interesting", "very_interesting", "very_not_interesting" And I would like them ordered dont_know, very_not_interesting, not_interesting, maybe_interesting, very_interesting – Liborio Francesco Cannici Jun 20 '10 at 12:03
  • Of course you can: `ggplot(mtcars, aes(factor(cyl))) + geom_bar() + scale_x_discrete(limits = c("6", "8", "4"))`. Here's an official documentation: http://had.co.nz/ggplot2/scale_discrete.html – aL3xa Jun 21 '10 at 00:05
  • Thabk you aL3xa... I am sorry to ask you this again... It works, but this line stat_bin(aes(label = paste(round((prop.table(..count..) * 100),2), "%", sep = "")) brings back the order as before. I gues it's because prop.table(..count..) has a different order. Any idea to how we can define the order in prop.table – Liborio Francesco Cannici Jun 21 '10 at 08:52
  • Check this one: `ggplot(mtcars, aes(factor(cyl))) + geom_bar() + stat_bin(aes(label = paste(prop.table(..count..) * 100, "%", sep = "")), vjust = -0.2, geom = "text", position = "identity")` and this one `ggplot(mtcars, aes(factor(cyl))) + geom_bar() + scale_x_discrete(limits = c("6", "8", "4")) + stat_bin(aes(label = paste(prop.table(..count..) * 100, "%", sep = "")), vjust = -0.2, geom = "text", position = "identity")` – aL3xa Jun 21 '10 at 14:34
2

Using sprintf:

sprintf("%d\n%2.2f%%", ft, prop.table(ft)*100)
Marek
  • 49,472
  • 15
  • 99
  • 121