I have a data table named dt, which is presented below (somewhat similar).
dt:
| Gender| Year | Length| Weight | Athlete_flag | Age|
|:-- |:---- |:------|:------ |:------------ |:---|
| M | 2009 | 188 | 89 | 1 |17 |
| F | 2007 | 170 | 65 | 1 |19 |
| M |2007 |172 |90 |0 |45 |
|M |2017 |160 |70 |0 |34 |
|F |2017 |160 |70 |0 |24 |
|M |2018 |160 |70 |0 |58 |
|F |2016 |160 |70 |0 |49 |
|F |2017 |160 |70 |0 |37 |
I would like to create a data table named dt_new with descriptive statistics of specific columns in the previous table by year. I would have two group columns, "Variable" and "Year". In other words, the table would look like following:
dt_new:
Variable|Year |Number of observations| Min|Mean |Max|
:------ |:----|:---- |:---|:------ |:--|
Length | 2007|2 |170 |171 |172|
Length | 2009|1 |188 |188 |188|
Length | 2016|1 |160 |160 |162|
Length | 2017|3 |160 |160 |160|
Length | 2018|1 |160 |160 |160|
Weight | 2007|2 |65 |77.5 |90 |
Weight | 2009|1 |89 |89 |89 |
Weight | 2016|1 |70 |70 |70 |
Weight | 2017|3 |70 |70 |70 |
Weight | 2018|1 |70 |70 |70 |
Age | 2007|2 |19 |32 |45 |
Age | 2009|1 |17 |17 |17 |
Age | 2016|1 |49 |49 |49 |
Age | 2017|3 |24 |31.66 |37 |
Age | 2018|1 |58 |58 |58 |
My plan was to add more columns with descriptive statistics such as percentiles, e.g. P99. I have used data.table and would prefer to find a solution with it. I am able to create a table named dt_incorrect as planned, however not by year, see below. My current code is:
dt_incorrect <- dt[,.("Variable" = colnames(dt[,c("Length","Width","Age")]),
"Number of observations" = nrow(dt[,c("Length","Width","Age")]),
"Min" = lapply(dt[,c("Length","Width","Age")], function(x) min(x, na.rm = T)),
"Mean" = lapply(dt[,c("Length","Width","Age")], function(x) mean(x, na.rm = T)),
"Max" = lapply(dt[,c("Length","Width","Age")], function(x) max(x, na.rm = T)))]
dt_incorrect:
Variable |Number of observations| Min |Mean |Max |
:------ |:---- |:------ |:------ |:---|
Length |8 |160 |166.25 |188 |
Weight |8 |65 |74.25 |90 |
Age |8 |17 |35.375 |58 |
Thank you in advance for all suggestions on how to fix this!