pivot_longer()
"lengthens" the data, increasing the number of rows and decreasing
the number of columns.
pivot_longer(
.df,
cols = everything(),
names_to = "name",
values_to = "value",
names_prefix = NULL,
names_sep = NULL,
names_pattern = NULL,
names_ptypes = NULL,
names_transform = NULL,
names_repair = "check_unique",
values_drop_na = FALSE,
values_ptypes = NULL,
values_transform = NULL,
fast_pivot = FALSE,
...
)
A data.table or data.frame
Columns to pivot. tidyselect
compatible.
Name of the new "names" column. Must be a string.
Name of the new "values" column. Must be a string.
Remove matching text from the start of selected columns using regex.
If names_to
contains multiple values, names_sep
takes
the same specification as separate()
.
If names_to
contains multiple values, names_pattern
takes
the same specification as extract()
, a regular expression containing matching groups.
A list of column name-prototype pairs. See ``?vctrs::`theory-faq-coercion``` for more info on vctrs coercion.
A list of column name-function pairs. Use these arguments if you need to change the types of specific columns.
Treatment of duplicate names. See ?vctrs::vec_as_names
for options/details.
If TRUE, rows will be dropped that contain NAs.
experimental: Fast pivoting. If TRUE
, the names_to
column will be returned as a factor
,
otherwise it will be a character
column. Defaults to FALSE
to match tidyverse semantics.
Additional arguments to passed on to methods.
df <- data.table(
x = 1:3,
y = 4:6,
z = c("a", "b", "c")
)
df %>%
pivot_longer(cols = c(x, y))
#> # A tidytable: 6 × 3
#> z name value
#> <chr> <chr> <int>
#> 1 a x 1
#> 2 b x 2
#> 3 c x 3
#> 4 a y 4
#> 5 b y 5
#> 6 c y 6
df %>%
pivot_longer(cols = -z, names_to = "stuff", values_to = "things")
#> # A tidytable: 6 × 3
#> z stuff things
#> <chr> <chr> <int>
#> 1 a x 1
#> 2 b x 2
#> 3 c x 3
#> 4 a y 4
#> 5 b y 5
#> 6 c y 6