Analogous function for dcast and melt in data.table

wider_dt(data, group, class_to_spread, value_to_spread = NULL, fill = NA)

longer_dt(
  data,
  group,
  gather_class = "class",
  gather_value = "value",
  na.rm = FALSE
)

Arguments

data

data.table

group

The unchanged group in the transformation

class_to_spread

The class of variable to spread

value_to_spread

The value of variable to spread. If missing, will guess automatically.

fill

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

gather_class

The column name of gathered class.

gather_value

The column name of gathered value.

na.rm

If TRUE, entries with NA values will be removed from the data.table.

Value

data.table

Details

In the nest_dt, the data would be nested to a column named `ndt`, which is short for nested 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) ) stocks %>% longer_dt(time) -> longer_stocks longer_stocks
#> time class value #> 1: 2009-01-01 X 0.747176602 #> 2: 2009-01-02 X -0.934819658 #> 3: 2009-01-03 X -0.466620448 #> 4: 2009-01-04 X -0.857190403 #> 5: 2009-01-05 X -1.524744178 #> 6: 2009-01-06 X 1.969424843 #> 7: 2009-01-07 X 0.463174707 #> 8: 2009-01-08 X -0.856152426 #> 9: 2009-01-09 X 0.648043285 #> 10: 2009-01-10 X 0.075803960 #> 11: 2009-01-01 Y 0.983522881 #> 12: 2009-01-02 Y -1.507081412 #> 13: 2009-01-03 Y 0.698054706 #> 14: 2009-01-04 Y -0.341697944 #> 15: 2009-01-05 Y 3.262412014 #> 16: 2009-01-06 Y -1.565412083 #> 17: 2009-01-07 Y -0.005787252 #> 18: 2009-01-08 Y 0.826478585 #> 19: 2009-01-09 Y 1.448866904 #> 20: 2009-01-10 Y 4.707889541 #> 21: 2009-01-01 Z -1.125798739 #> 22: 2009-01-02 Z -1.924185745 #> 23: 2009-01-03 Z 0.316903698 #> 24: 2009-01-04 Z 3.079441321 #> 25: 2009-01-05 Z 2.253347839 #> 26: 2009-01-06 Z -1.495950095 #> 27: 2009-01-07 Z -2.405222236 #> 28: 2009-01-08 Z -1.696700139 #> 29: 2009-01-09 Z -3.489263524 #> 30: 2009-01-10 Z 0.426738459 #> time class value
longer_stocks %>% wider_dt(time,class)
#> time X Y Z #> 1: 2009-01-01 0.74717660 0.983522881 -1.1257987 #> 2: 2009-01-02 -0.93481966 -1.507081412 -1.9241857 #> 3: 2009-01-03 -0.46662045 0.698054706 0.3169037 #> 4: 2009-01-04 -0.85719040 -0.341697944 3.0794413 #> 5: 2009-01-05 -1.52474418 3.262412014 2.2533478 #> 6: 2009-01-06 1.96942484 -1.565412083 -1.4959501 #> 7: 2009-01-07 0.46317471 -0.005787252 -2.4052222 #> 8: 2009-01-08 -0.85615243 0.826478585 -1.6967001 #> 9: 2009-01-09 0.64804329 1.448866904 -3.4892635 #> 10: 2009-01-10 0.07580396 4.707889541 0.4267385
longer_stocks %>% mutate_dt(one = 1) %>% wider_dt(time,class,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