how to calculate percentage from a vector of counts

jaytika saharan picture jaytika saharan · Aug 13, 2013 · Viewed 74.3k times · Source

I have a data.frame that looks like this:

> dat <- data.frame(Operation = c("Login", "Posted", "Deleted"), `Total Count` = c(5, 25, 40), check.names = FALSE)
> dat
  Operation Total Count
1     Login           5
2    Posted          25
3   Deleted          40

I want to calculate the percentage for each Operation, e.g., what percentage of Operations were Login. I'd expect a result like:

  Operation Total Count Percentage
1     Login           5 0.07142857
2    Posted          25 0.35714286
3   Deleted          40 0.57142857

Since the counts are already summarized, table() doesn't work:

> table(dat$`Total Count`)

 5 25 40 
 1  1  1 

Answer

Peyton picture Peyton · Aug 13, 2013

Call your column Total.Count instead of Total Count; spaces in names don't work well.

If you have your data in a data frame called, say, my.df:

my.df$Pct <- my.df$Total.Count / sum(my.df$Total.Count)
my.df
##   Operation Total.Count        Pct
## 1     Login           5 0.07142857
## 2    Posted          25 0.35714286
## 3   Deleted          40 0.57142857