Skip to content

Instantly share code, notes, and snippets.

@jnolis
Last active October 29, 2018 04:07
Show Gist options
  • Save jnolis/df2a0f02457be2febed5f09202159b20 to your computer and use it in GitHub Desktop.
Save jnolis/df2a0f02457be2febed5f09202159b20 to your computer and use it in GitHub Desktop.
Example spread
library(tidyverse)
# here is a table that spreads the way you'd want (with two rows):
tribble(
~a, ~b, ~c,
"a", "x", 3,
"a", "y", 2,
"b", "x", 4,
"b", "y", 7
) %>% spread(b,c)
# # A tibble: 2 x 3
# a x y
# <chr> <dbl> <dbl>
# 1 a 3 2
# 2 b 4 7
# here is a table that doesn't spread the way I would want (it has four rows).
# I happen to know that it's because the function doesn't know how to collapse 'd',
# but it often don't notice it happen often at the time:
tribble(
~a, ~b, ~c, ~d,
"a", "x", 3, "r",
"a", "y", 2, "s",
"b", "x", 4, "t",
"b", "y", 7, "u"
) %>% spread(b,c)
# # A tibble: 4 x 4
# a d x y
# <chr> <chr> <dbl> <dbl>
# 1 a r 3 NA
# 2 a s NA 2
# 3 b t 4 NA
# 4 b u NA 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment