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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With