Created
October 15, 2014 16:31
-
-
Save mmparker/8c5ed6617d8f9f7e5fc9 to your computer and use it in GitHub Desktop.
Percentage calculation snippet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Calculate percent of responses by department | |
| # The input here is a subset of kano_questions - all of the | |
| # responses related to one item | |
| x_by_dept <- ddply(subset(x, !is.na(department)), # Dropping that person with no department | |
| .var = "department", # I'm going to split x by department | |
| .fun = function(y) { # Writing a custom, nameless function to apply | |
| # to each chunk of x | |
| # The best way to see how this works is to make your own y | |
| # with y <- subset(x, department %in% "CS") and | |
| # step through each of the code bits below - then look | |
| # at the output of each. What does y look like? | |
| # First, I want to know how many respondents found this item | |
| # Attractive, Must-be, etc. This is a quick way to aggregate | |
| # their responses. y is the subset of x with just one | |
| # department's responses in it; "kano_cat" is the variable I'm | |
| # counting. | |
| dept_count <- count(y, "kano_cat") | |
| # What does dept_count look like? | |
| # Now I'll add proportion who gave each response. | |
| # mutate() is one way to do this, but the main | |
| # thing is that I'm calculating the proportion | |
| # by dividng the column of counts (freq) by | |
| # the total number of respondents. | |
| # Since this is the last "object" produced | |
| # in the function, I don't bother to assign it; | |
| # R will just return it up to ddply, which will | |
| # stack the outputs of all the groups together | |
| # nicely. | |
| mutate(dept_count, | |
| prop = freq / sum(freq) | |
| ) | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment