Skip to content

Instantly share code, notes, and snippets.

@gadenbuie
Last active March 12, 2019 16:15
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 gadenbuie/f99db93cef4e5aa543a62fd3e694d43d to your computer and use it in GitHub Desktop.
Save gadenbuie/f99db93cef4e5aa543a62fd3e694d43d to your computer and use it in GitHub Desktop.
library(tidyverse)

spread_var <- function(df, varname) {
  varname <- rlang::enquo(varname)
  spread(df, key = !!varname, count)
}

head(tidyr::table2)
#> # A tibble: 6 x 4
#>   country      year type           count
#>   <chr>       <int> <chr>          <int>
#> 1 Afghanistan  1999 cases            745
#> 2 Afghanistan  1999 population  19987071
#> 3 Afghanistan  2000 cases           2666
#> 4 Afghanistan  2000 population  20595360
#> 5 Brazil       1999 cases          37737
#> 6 Brazil       1999 population 172006362

tidyr::table2 %>% 
  spread_var(type)
#> # A tibble: 6 x 4
#>   country      year  cases population
#>   <chr>       <int>  <int>      <int>
#> 1 Afghanistan  1999    745   19987071
#> 2 Afghanistan  2000   2666   20595360
#> 3 Brazil       1999  37737  172006362
#> 4 Brazil       2000  80488  174504898
#> 5 China        1999 212258 1272915272
#> 6 China        2000 213766 1280428583

Created on 2019-03-12 by the reprex package (v0.2.1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment