Marie
Marie

Reputation: 71

Returning cumulative percentage table at once

I want to know how can I get a cumulative percentage in the table or data.frame

df <- data.frame(Alphabet = c("A", "A","A","A","A", "B", "B", "B"), 
         Value = c(1,1, 2,2,3,2,2,4))

Ideal output will look like

   1    2      3      4
A 40%  80%    100%   100%
B  0%  66.6%  66.6%  100%

Upvotes: 1

Views: 342

Answers (1)

akrun
akrun

Reputation: 887551

We could use rowCumsums on a prop.table

library(matrixStats)
tbl <- prop.table(table(df), 1) * 100
tbl[] <- rowCumsums(tbl)
names(dimnames(tbl)) <- NULL
tbl[] <-  paste0(sub("^([^.]+)(\\.[^0]).*", "\\1\\2", tbl), "%")
tbl
#    1   2     3     4   
#A 40% 80%   100%  100%
#B 0%  66.6% 66.6% 100%

Upvotes: 2

Related Questions