Analogous function for pivot_wider in tidyr.

wider_dt(
  data,
  group_to_keep = NULL,
  name_to_spread,
  value_to_spread = NULL,
  fill = NA
)

Arguments

data

data.table

group_to_keep

The unchanged group in the transformation. Could use integer vector, character vector or regular expression(to match the column names). If NULL, use all other variables.

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.

fill

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

Value

data.table

See also

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
#> time variable value #> 1: 2009-01-01 X -0.15569378 #> 2: 2009-01-02 X 0.43388979 #> 3: 2009-01-03 X -0.38195111 #> 4: 2009-01-04 X 0.42418757 #> 5: 2009-01-05 X 1.06310200 #> 6: 2009-01-06 X 1.04871262 #> 7: 2009-01-07 X -0.03810289 #> 8: 2009-01-08 X 0.48614892 #> 9: 2009-01-09 X 1.67288261 #> 10: 2009-01-10 X -0.35436116 #> 11: 2009-01-01 Y 1.89269577 #> 12: 2009-01-02 Y 2.63365271 #> 13: 2009-01-03 Y -0.59328005 #> 14: 2009-01-04 Y -0.77442715 #> 15: 2009-01-05 Y -1.57086531 #> 16: 2009-01-06 Y -2.11347373 #> 17: 2009-01-07 Y -1.59108286 #> 18: 2009-01-08 Y -3.51255086 #> 19: 2009-01-09 Y -1.38107579 #> 20: 2009-01-10 Y -1.11708399 #> 21: 2009-01-01 Z -2.14665331 #> 22: 2009-01-02 Z 0.90850853 #> 23: 2009-01-03 Z 3.91381968 #> 24: 2009-01-04 Z -0.83553061 #> 25: 2009-01-05 Z -5.59764184 #> 26: 2009-01-06 Z 1.03414915 #> 27: 2009-01-07 Z -1.76719781 #> 28: 2009-01-08 Z 2.27439944 #> 29: 2009-01-09 Z 8.50740184 #> 30: 2009-01-10 Z 1.69943377 #> time variable value
longer_stocks %>% wider_dt("time","variable","value")
#> time X Y Z #> 1: 2009-01-01 -0.15569378 1.8926958 -2.1466533 #> 2: 2009-01-02 0.43388979 2.6336527 0.9085085 #> 3: 2009-01-03 -0.38195111 -0.5932800 3.9138197 #> 4: 2009-01-04 0.42418757 -0.7744272 -0.8355306 #> 5: 2009-01-05 1.06310200 -1.5708653 -5.5976418 #> 6: 2009-01-06 1.04871262 -2.1134737 1.0341492 #> 7: 2009-01-07 -0.03810289 -1.5910829 -1.7671978 #> 8: 2009-01-08 0.48614892 -3.5125509 2.2743994 #> 9: 2009-01-09 1.67288261 -1.3810758 8.5074018 #> 10: 2009-01-10 -0.35436116 -1.1170840 1.6994338
longer_stocks %>% mutate_dt(one = 1) %>% wider_dt("time","variable","one")
#> time X Y Z #> 1: 2009-01-01 1 1 1 #> 2: 2009-01-02 1 1 1 #> 3: 2009-01-03 1 1 1 #> 4: 2009-01-04 1 1 1 #> 5: 2009-01-05 1 1 1 #> 6: 2009-01-06 1 1 1 #> 7: 2009-01-07 1 1 1 #> 8: 2009-01-08 1 1 1 #> 9: 2009-01-09 1 1 1 #> 10: 2009-01-10 1 1 1