一次返回累积百分比表

时间:2017-08-25 21:30:01

标签: r

我想知道如何在表格或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))

理想的输出看起来像

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

1 个答案:

答案 0 :(得分:2)

我们可以在rowCumsums

上使用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%