tidyr (version 0.4.0)

unnest: Unnest a list column.

Description

If you have a list-column, this makes each element of the list it's own row. List-columns can either be atomic vectors or data frames. Each row must have the same number of entries.

Usage

unnest(data, ..., .drop = NA)

Arguments

data
A data frame.
...
Specification of columns to nest. Use bare variable names or functions of variables. If omitted, defaults to all list-cols.
.drop
Should additional list columns be dropped? By default, unnest will drop them if unnesting the specified columns requires the rows to be duplicated.

See Also

nest for the inverse operation.

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

Examples

Run this code
library(dplyr)
df <- data_frame(
  x = 1:3,
  y = c("a", "d,e,f", "g,h")
)
df %>%
  transform(y = strsplit(y, ",")) %>%
  unnest(y)

# Or just
df %>%
  unnest(y = strsplit(y, ","))

# It also works if you have a column that contains other data frames!
df <- data_frame(
  x = 1:2,
  y = list(
   data_frame(z = 1),
   data_frame(z = 3:4)
 )
)
df %>% unnest(y)

# You can also unnest multiple columns simultaneously
df <- data_frame(
 a = list(c("a", "b"), "c"),
 b = list(1:2, 3),
 c = c(11, 22)
)
df %>% unnest(a, b)
# If you omit the column names, it'll unnest all list-cols
df %>% unnest()

# Nest and unnest are inverses
df <- data.frame(x = c(1, 1, 2), y = 3:1)
df %>% nest(y)
df %>% nest(y) %>% unnest()

Run the code above in your browser using DataCamp Workspace