tidyr (version 0.3.1)

expand: Expand data frame to include all combinations of values

Description

expand() is often useful in conjunction with left_join if you want to convert implicit missing values to explicit missing values. Or you can use it in conjunction with anti_join() to figure out which combinations are missing.

Usage

expand(data, ...)

Arguments

data
A data frame
...
Specification of columns to expand.

To find all unique combinations of x, y and z, including those not found in the data, supply each variable as a separate argument. To find only the combinations that occur in the data, supply them as a single a

See Also

complete for a common application of expand: completing a data frame with missing combinations.

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

Examples

Run this code
# All possible combinations of vs & cyl, even those that aren't
# present in the data
expand(mtcars, vs, cyl)

# Only combinations of vs and cyl that appear in the data
expand(mtcars, c(vs, cyl))

library(dplyr)
# Each person was given one of two treatments, repeated three times
# But some of the replications haven't happened yet, so we have
# incomplete data:
experiment <- data_frame(
  name = rep(c("Alex", "Robert", "Sam"), c(3, 2, 1)),
  trt  = rep(c("a", "b", "a"), c(3, 2, 1)),
  rep = c(1, 2, 3, 1, 2, 1),
  measurment_1 = runif(6),
  measurment_2 = runif(6)
)

# We can figure out the complete set of data with expand()
# Each person only gets one treatment, so we nest name and trt together:
complete <- expand(experiment, c(name, trt), rep)
complete

# We can use anti_join to figure out which observations are missing
complete %>% anti_join(experiment)

# And use right_join to add in the appropriate missing values to the
# original data
experiment %>% right_join(complete)
# Or use complete() which wraps up this common pattern
complete(experiment, c(name, trt), rep)

Run the code above in your browser using DataCamp Workspace