Learn R Programming

tidyfst (version 0.8.8)

wider_dt: Pivot data from long to wide

Description

Analogous function for pivot_wider in tidyr.

Usage

wider_dt(
  data,
  ...,
  name_to_spread,
  value_to_spread = NULL,
  fun = identity,
  fill = NA
)

Arguments

data

data.table

...

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

name_to_spread

Chracter.One column name of class to spread

value_to_spread

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

fun

Should the data be aggregated before casting? If the formula doesn't identify a single observation for each cell, then aggregation defaults to length with a message. To use multiple aggregation functions, pass a list.

fill

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

Value

data.table

Details

The parameter of `name_to_spread` and `value_to_spread` should always be provided and should be explicit called (with the parameter names attached).

See Also

longer_dt, dcast, pivot_wider

Examples

Run this code
# NOT RUN {
 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_to_spread = "name",
            value_to_spread = "value")

 longer_stocks %>%
   mutate_dt(one = 1) %>%
   wider_dt("time",
            name_to_spread = "name",
            value_to_spread = "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_to_spread = "v4",
           name_to_spread = ".",
           fun = sum)
# }

Run the code above in your browser using DataLab