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