dt_pivot_wider() "widens" data, increasing the number of columns and decreasing the number of rows. The inverse transformation is dt_pivot_longer(). Syntax based on the tidyr equivalents.

dt_pivot_longer(
  dt_,
  cols = NULL,
  names_to = "name",
  values_to = "value",
  values_drop_na = FALSE,
  ...
)

Arguments

dt_

The data table to pivot longer

cols

Column selection. If empty, uses all columns. Can use -colname to unselect column(s)

names_to

Name of the new "names" column. Must be a string.

values_to

Name of the new "values" column. Must be a string.

values_drop_na

If TRUE, rows will be dropped that contain NAs.

...

Additional arguments to pass to `melt.data.table()`

Value

A reshaped data.table into longer format

Examples


library(data.table)
example_dt <- data.table(x = c(1, 2, 3), y = c(4, 5, 6), z = c("a", "b", "c"))

dt_pivot_longer(example_dt,
  cols = c(x, y),
  names_to = "stuff",
  values_to = "things"
)
#>    z stuff things
#> 1: a     x      1
#> 2: b     x      2
#> 3: c     x      3
#> 4: a     y      4
#> 5: b     y      5
#> 6: c     y      6

dt_pivot_longer(example_dt,
  cols = -z,
  names_to = "stuff",
  values_to = "things"
)
#>    z stuff things
#> 1: a     x      1
#> 2: b     x      2
#> 3: c     x      3
#> 4: a     y      4
#> 5: b     y      5
#> 6: c     y      6