spread

0th

Percentile

Spread a key-value pair across multiple columns.

Spread a key-value pair across multiple columns.

Usage
spread(data, key, value, fill = NA, convert = FALSE, drop = TRUE,
  sep = NULL)
Arguments
data
A data frame.
key
The bare (unquoted) name of the column whose values will be used as column headings.
value
The bare (unquoted) name of the column whose values will populate the cells.
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 replaced by fill.
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. If the class of the value column was factor or date, note that will not be true of the new columns that are produced, which are coerced to character before type conversion.
drop
If FALSE, will keep factor levels that don't appear in the data, filling in missing combinations with fill.
sep
If NULL, the column names will be taken from the values of key variable. If non-NULL, the column names will be given by "<key_name><sep><key_value>".
See Also

spread_ for a version that uses regular evaluation and is suitable for programming with.

Aliases
  • spread
Examples
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)

# Use 'convert = TRUE' to produce variables of mixed type
df <- data.frame(row = rep(c(1, 51), each = 3),
                 var = c("Sepal.Length", "Species", "Species_num"),
                 value = c(5.1, "setosa", 1, 7.0, "versicolor", 2))
df %>% spread(var, value) %>% str
df %>% spread(var, value, convert = TRUE) %>% str
Documentation reproduced from package tidyr, version 0.6.2, License: MIT + file LICENSE

Community examples

rachhpal1176 at Jan 30, 2019 tidyr v0.8.2

student <- c('Gurnoor', 'Gurnoor', 'Gurnoor', 'Gurnoor', 'Gurnoor', 'Gurnoor', 'Dhruv', 'Dhruv', 'Dhruv', 'Dhruv', 'Dhruv', 'Dhruv') subject <- c('English', 'Hindi', 'Punjabi', 'Maths', 'Science', 'Social Science', 'English', 'Hindi', 'Punjabi', 'Maths', 'Science', 'Social Science') marks <- as.character ( c('38/40', '40/40', '32/40', '29/40', '27/40', '35/40', '30/40', '33/40', '36/40', '31/40', '39/40', '34/40') ) reportCard_Nov18 <- data.frame(Student = student, Subject = subject, Marks = marks) reportCard_Nov18.wide <- reportCard_Nov18 %>% spread(Student, Marks) reportCard_Nov18.wide