Pivot data from wide to long
pivot_longer()
"lengthens" data, increasing the number of rows and
decreasing the number of columns. The inverse transformation is
pivot_wider()
Learn more in vignette("pivot")
.
pivot_longer( data, cols, names_to = "name", names_prefix = NULL, names_sep = NULL, names_pattern = NULL, names_ptypes = list(), names_transform = list(), names_repair = "check_unique", values_to = "value", values_drop_na = FALSE, values_ptypes = list(), values_transform = list(), ... )
data |
A data frame to pivot. |
cols |
< |
names_to |
A string specifying the name of the column to create
from the data stored in the column names of Can be a character vector, creating multiple columns, if
|
names_prefix |
A regular expression used to remove matching text from the start of each variable name. |
names_sep, names_pattern |
If
If these arguments do not give you enough control, use
|
names_ptypes, values_ptypes |
A list of column name-prototype pairs.
A prototype (or ptype for short) is a zero-length vector (like |
names_transform, values_transform |
A list of column name-function pairs.
Use these arguments if you need to change the types of specific columns.
For example, If not specified, the type of the columns generated from |
names_repair |
What happens if the output has invalid column names?
The default, |
values_to |
A string specifying the name of the column to create
from the data stored in cell values. If |
values_drop_na |
If |
... |
Additional arguments passed on to methods. |
pivot_longer()
is an updated approach to gather()
, designed to be both
simpler to use and to handle more use cases. We recommend you use
pivot_longer()
for new code; gather()
isn't going away but is no longer
under active development.
# See vignette("pivot") for examples and explanation # Simplest case where column names are character data relig_income relig_income %>% pivot_longer(!religion, names_to = "income", values_to = "count") # Slightly more complex case where columns have common prefix, # and missing missings are structural so should be dropped. billboard billboard %>% pivot_longer( cols = starts_with("wk"), names_to = "week", names_prefix = "wk", values_to = "rank", values_drop_na = TRUE ) # Multiple variables stored in column names who %>% pivot_longer( cols = new_sp_m014:newrel_f65, names_to = c("diagnosis", "gender", "age"), names_pattern = "new_?(.*)_(.)(.*)", values_to = "count" ) # Multiple observations per row anscombe anscombe %>% pivot_longer(everything(), names_to = c(".value", "set"), names_pattern = "(.)(.)" )
Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.