若要執行這項操作的一種方式會如下所示。
您可以計算總計的群組使用 rxSummary() 的加總,然後使用它來計算群組百分比︰
df <- data.frame(g = c('1', '0', '1', '0'), a=c(1, 2, 3, 4)) sums.within.g <- rxSummary(a ~ g, data = df, summaryStats = "Sum")
sums.within.g <- sums.within.g$categorical[[1]][,3]
numRows <- length(unique(df$g))
totSum <- cumsum(sums.within.g)
totSum <- totSum[length(totSum)]
df.percentages <- sums.within.g / totSum
names(df.percentages) <- levels(df$g)
> df.percentages
0 1
0.6 0.4