Notice: This website is an unofficial Microsoft Knowledge Base (hereinafter KB) archive and is intended to provide a reliable access to deleted content from Microsoft KB. All KB articles are owned by Microsoft Corporation. Read full disclaimer for more details.

How can I compute group percentages for a categorical variable?


View products that this article applies to.

One way to do this is to use rxSummary() to compute the group sums and then calculate the group percentages from these categorical counts.

 

Here is a simple example that shows how to do this:

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

↑ Back to the top


Keywords: kb

↑ Back to the top

Article Info
Article ID : 3104216
Revision : 1
Created on : 1/7/2017
Published on : 10/29/2015
Exists online : False
Views : 65