Closed
Description
library(dplyr)
library(tidyr)
# From Jenny Bryan --------------------------------------------------------
input <- frame_data(
~hw, ~name, ~mark, ~pr,
"hw1", "anna", 95, "ok",
"hw1", "alan", 90, "meh",
"hw1", "carl", 85, "ok",
"hw2", "alan", 70, "meh",
"hw2", "carl", 80, "ok"
)
# Want:
input %>%
gather(key = element, value = score, mark, pr) %>%
unite(thing, hw, element, remove = TRUE) %>%
spread(thing, score, convert = TRUE)
# With multispread - still have to go through untidy/molten form,
# which loses variable names
input %>%
gather(mark, pr, key = element, value = score) %>%
spread(c(hw, element), score, convert = TRUE)
# http://stackoverflow.com/questions/27247078 -----------------------------
df <- frame_data(
~id, ~type, ~transactions, ~amount,
20, "income", 20, 100,
20, "expense", 25, 95,
30, "income", 50, 300,
30, "expense", 45, 250
)
df %>%
gather(var, val, transactions:amount) %>%
unite(var2, type, var) %>%
spread(var2, val)
# With multispread - still have to go through untidy/molten form
df %>%
gather(var, val, transactions:amount) %>%
spread(c(type, var), val)
# http://stackoverflow.com/questions/24929954 -----------------------------
df <- expand.grid(Year = 2000:2014, Product = c("A", "B"), Country = c("AI", "EI")) %>%
tbl_df() %>%
select(Product, Country, Year) %>%
mutate(value = rnorm(nrow(.))) %>%
filter((Product == "A" & Country == "AI") | (Product == "B" & Country == "EI"))
df %>%
unite(Prod_Count, Product, Country) %>%
spread(Prod_Count, value)
# If we had multi-spread:
df %>%
spread(c(Product, Country), value)