behead | R Documentation |
behead()
takes one level of headers from a pivot table and
makes it part of the data. Think of it like tidyr::gather()
, except that
it works when there is more than one row of headers (or more than one column
of row-headers), and it only works on tables that have first come through
as_cells()
or tidyxl::xlsx_cells()
.
behead( cells, direction, name, values = NULL, types = data_type, formatters = list(), drop_na = TRUE ) behead_if( cells, ..., direction, name, values = NULL, types = data_type, formatters = list(), drop_na = TRUE )
cells |
Data frame. The cells of a pivot table, usually the output of
|
direction |
The direction between a data cell and its header, one of
|
name |
A name to give the new column that will be created, e.g.
|
values |
Optional. The column of |
types |
The name of the column that names the data type of each cell.
Usually called |
formatters |
A named list of functions for formatting each data type in
a set of headers of mixed data types, e.g. when some headers are dates and
others are characters. These can be given as |
drop_na |
logical Whether to filter out headers that have |
... |
Passed to dplyr::filter. logical predicates defined in terms of
the variables in The arguments in |
A data frame
# A simple table with a row of headers (x <- data.frame(a = 1:2, b = 3:4)) # Make a tidy representation of each cell (cells <- as_cells(x, col_names = TRUE)) # Strip the cells in row 1 (the original headers) and use them as data behead(cells, "N", foo) # More complex example: pivot table with several layers of headers (x <- purpose$`up-left left-up`) # Make a tidy representation cells <- as_cells(x) head(cells) tail(cells) # Strip the headers and make them into data tidy <- cells %>% behead("up-left", Sex) %>% behead("up", `Sense of purpose`) %>% behead("left-up", `Highest qualification`) %>% behead("left", `Age group (Life-stages)`) %>% dplyr::mutate(count = as.integer(chr)) %>% dplyr::select(-row, -col, -data_type, -chr) head(tidy) # Check against the provided 'tidy' version of the data. dplyr::anti_join(tidy, purpose$Tidy) # The provided 'tidy' data is missing a row for Male 15-24-year-olds with a # postgraduate qualification and a sense of purpose between 0 and 6. That # seems to have been an oversight by Statistics New Zealand. cells <- tibble::tribble( ~X1, ~adult, ~juvenile, "LION", 855, 677, "male", 496, 322, "female", 359, 355, "TIGER", 690, 324, "male", 381, 222, "female", 309, 102 ) cells <- as_cells(cells, col_names = TRUE) cells %>% behead_if(chr == toupper(chr), direction = "left-up", name = "species") %>% behead("left", "sex") %>% behead("up", "age") %>% dplyr::select(species, sex, age, population = dbl)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.