tidyr (version 0.3.0)

spread: Spread a key-value pair across multiple columns.

Description

Spread a key-value pair across multiple columns.

Usage

spread(data, key, value, fill = NA, convert = FALSE, drop = TRUE)

Arguments

data
A data frame.
key,value
Bare (unquoted) names of key and value columns.
fill
If set, missing values will be replaced with this value. Note that there are two types of missingness in the input: explicit missing values (i.e. NA), and implicit missings, rows that simply aren't present. Both types of missing value will be
convert
If TRUE, type.convert with asis = TRUE will be run on each of the new columns. This is useful if the value column was a mix of variables that was coerced to a string.
drop
If FALSE, will keep factor levels that don't appear in the data, filling in missing combinations with fill.

Examples

Run this code
library(dplyr)
stocks <- data.frame(
  time = as.Date('2009-01-01') + 0:9,
  X = rnorm(10, 0, 1),
  Y = rnorm(10, 0, 2),
  Z = rnorm(10, 0, 4)
)
stocksm <- stocks %>% gather(stock, price, -time)
stocksm %>% spread(stock, price)
stocksm %>% spread(time, price)

# Spread and gather are complements
df <- data.frame(x = c("a", "b"), y = c(3, 4), z = c(5, 6))
df %>% spread(x, y) %>% gather(x, y, a:b, na.rm = TRUE)

Run the code above in your browser using DataCamp Workspace