wider_dt: Pivot data from long to wide

View source: R/wider_dt.R

wider_dtR Documentation

Pivot data from long to wide

Description

Transform a data frame from long format to wide by increasing the number of columns and decreasing the number of rows.

Usage

wider_dt(.data, ..., name, value = NULL, fun = NULL, fill = NA)

Arguments

.data

A data.frame

...

Optional. The unchanged group in the transformation. Could use integer vector, could receive what select_dt receives.

name

Chracter.One column name of class to spread

value

Chracter.One column name of value to spread. If NULL, use all other variables.

fun

Should the data be aggregated before casting? Defaults to NULL, which uses length for aggregation. If a function is provided, with aggregated by this function.

fill

Value with which to fill missing cells. Default uses NA.

Details

The parameter of 'name' and 'value' should always be provided and should be explicit called (with the parameter names attached).

Value

data.table

See Also

longer_dt, dcast, pivot_wider

Examples

 stocks = data.frame(
   time = as.Date('2009-01-01') + 0:9,
   X = rnorm(10, 0, 1),
   Y = rnorm(10, 0, 2),
   Z = rnorm(10, 0, 4)
 ) %>%
   longer_dt(time) -> longer_stocks

 longer_stocks

 longer_stocks %>%
   wider_dt("time",
            name = "name",
            value = "value")

 longer_stocks %>%
   mutate_dt(one = 1) %>%
   wider_dt("time",
            name = "name",
            value = "one")

## using "fun" parameter for aggregation
DT <- data.table(v1 = rep(1:2, each = 6),
                 v2 = rep(rep(1:3, 2), each = 2),
                 v3 = rep(1:2, 6),
                 v4 = rnorm(6))
## for each combination of (v1, v2), add up all values of v4
DT %>%
  wider_dt(v1,v2,
           value = "v4",
           name = ".",
           fun = sum)

tidyfst documentation built on Sept. 16, 2024, 9:06 a.m.