【问题标题】:Returning cumulative percentage table at once一次返回累计百分比表
【发布时间】:2017-08-25 21:30:00
【问题描述】:

我想知道如何在 table 或 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%

【问题讨论】:

    标签: r


    【解决方案1】:

    我们可以在prop.table 上使用rowCumsums

    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%
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-24
      • 2017-03-03
      • 1970-01-01
      • 2018-09-24
      相关资源
      最近更新 更多