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

unnest(data, ..., .drop = NA, .id = NULL, .sep = NULL)

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.

.id

Data frame idenfier - if supplied, will create a new column with name .id, giving a unique identifer. This is most useful if the list column is named.

.sep

If non-NULL, the names of unnested data frame columns will combine the name of the original list-col with the names from nested data frame, separated by .sep.

See also

nest for the inverse operation. unnest_ for a version that uses regular evaluation and is suitable for programming with.

Examples

library(dplyr) df <- data_frame( x = 1:3, y = c("a", "d,e,f", "g,h") ) df %>% transform(y = strsplit(y, ",")) %>% unnest(y)
#> x y #> 1 1 a #> 2 2 d #> 3 2 e #> 4 2 f #> 5 3 g #> 6 3 h
# Or just df %>% unnest(y = strsplit(y, ","))
#> # A tibble: 6 × 2 #> x y #> <int> <chr> #> 1 1 a #> 2 2 d #> 3 2 e #> 4 2 f #> 5 3 g #> 6 3 h
# 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)
#> # A tibble: 3 × 2 #> x z #> <int> <dbl> #> 1 1 1 #> 2 2 3 #> 3 2 4
# 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)
#> # A tibble: 3 × 3 #> c a b #> <dbl> <chr> <dbl> #> 1 11 a 1 #> 2 11 b 2 #> 3 22 c 3
# If you omit the column names, it'll unnest all list-cols df %>% unnest()
#> # A tibble: 3 × 3 #> c a b #> <dbl> <chr> <dbl> #> 1 11 a 1 #> 2 11 b 2 #> 3 22 c 3
# Nest and unnest are inverses df <- data.frame(x = c(1, 1, 2), y = 3:1) df %>% nest(y)
#> # A tibble: 2 × 2 #> x data #> <dbl> <list> #> 1 1 <tibble [2 × 1]> #> 2 2 <tibble [1 × 1]>
df %>% nest(y) %>% unnest()
#> # A tibble: 3 × 2 #> x y #> <dbl> <int> #> 1 1 3 #> 2 1 2 #> 3 2 1
# If you have a named list-column, you may want to supply .id df <- data_frame( x = 1:2, y = list(a = 1, b = 3:4) ) unnest(df, .id = "name")
#> # A tibble: 3 × 3 #> x y name #> <int> <dbl> <int> #> 1 1 1 1 #> 2 2 3 2 #> 3 2 4 2