Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to calculate percentage from a vector of counts

Tags:

r

percentage

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 
like image 951
jaytika saharan Avatar asked Aug 13 '13 12:08

jaytika saharan


2 Answers

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
like image 63
Peyton Avatar answered Oct 21 '22 21:10

Peyton


You can use function prop.table() to calculate percentages (assuming that column name is TotalCount).

df$percent<- prop.table(df$TotalCount)

df
  Operation TotalCount    percent
1     Login          5 0.07142857
2    Posted         25 0.35714286
3   Deleted         40 0.57142857
like image 44
Didzis Elferts Avatar answered Oct 21 '22 20:10

Didzis Elferts