Skip to content

Instantly share code, notes, and snippets.

@ChrisBeeley
Created November 13, 2018 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChrisBeeley/0576e73951506a84a1a5cfd15cbccdbe to your computer and use it in GitHub Desktop.
Save ChrisBeeley/0576e73951506a84a1a5cfd15cbccdbe to your computer and use it in GitHub Desktop.
This is just a reprex of a thing that I couldn't replicate on Stack Overflow https://stackoverflow.com/questions/34860535/how-to-use-dplyr-to-generate-a-frequency-table/34860724
library(tidyverse)
#> Warning: package 'tidyverse' was built under R version 3.4.4
#> -- Attaching packages ----------------------------------------------------------------------------------------------- tidyverse 1.2.1 --
#> v ggplot2 3.0.0 v purrr 0.2.4
#> v tibble 1.4.2 v dplyr 0.7.6
#> v tidyr 0.8.1 v stringr 1.3.0
#> v readr 1.1.1 v forcats 0.3.0
#> Warning: package 'ggplot2' was built under R version 3.4.4
#> Warning: package 'tibble' was built under R version 3.4.4
#> Warning: package 'readr' was built under R version 3.4.4
#> Warning: package 'purrr' was built under R version 3.4.4
#> Warning: package 'dplyr' was built under R version 3.4.4
#> Warning: package 'stringr' was built under R version 3.4.4
#> Warning: package 'forcats' was built under R version 3.4.4
#> -- Conflicts -------------------------------------------------------------------------------------------------- tidyverse_conflicts() --
#> x dplyr::filter() masks stats::filter()
#> x dplyr::lag() masks stats::lag()
x = "RespondentID Color Gender
1 1503 Red F
2 1653 NA M
3 1982 Red F
4 4862 Red NA
15 4880 Blue M"
df = read.table(text = x, header = TRUE)
gather(df, "var", "value", -RespondentID) %>%
count(var, value) %>%
mutate(prop = prop.table(n))
#> Warning: attributes are not identical across measure variables;
#> they will be dropped
#> Warning: package 'bindrcpp' was built under R version 3.4.4
#> # A tibble: 6 x 4
#> var value n prop
#> <chr> <chr> <int> <dbl>
#> 1 Color Blue 1 0.1
#> 2 Color Red 3 0.3
#> 3 Color <NA> 1 0.1
#> 4 Gender F 2 0.2
#> 5 Gender M 2 0.2
#> 6 Gender <NA> 1 0.1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment