Question: My goal is to write a function where I group over something and then assign the result to a *column name specified in advance*. The function below does not accomplish this and returns a data.table with the column name "colname1". Does anyone know how to write the function that the column name becomes "mean\_price"?

```
DT_example <- data.table(price = c(1,2,3,4,5,6,7,8), type = c("a","a","a","a","b","b","b","b"))

compute_price_mean <- function(DT, colname1, p, t) {
    DT[, .(colname1 = mean(get(p))), by = t]
}

result <- compute_price_mean(DT_example, "mean_price", "price", "type")

```

Answer: 
We can use `setNames`

```
library(data.table)
compute_price_sum <- function(DT, colname1, p, t) {
   DT_example[, setNames(list(mean(get(p))), colname1), by = t]
}

compute_price_sum(DT_example, "mean_price", "price", "type")
#   type mean_price
#1:    a        2.5
#2:    b        6.5

```
We can use `tidyverse` 

```
library(dplyr)
library(data.table)
compute_price_mean <- function(DT, colname1, p, t) {
    DT %>%
      group_by_at(t) %>% 
      summarise(!! colname1 := mean(!! rlang::sym(p)))
   }
compute_price_mean(DT_example, "mean_price", "price", "type")
# A tibble: 2 x 2
#  type  mean_price
# <chr>      <dbl>
#1 a            2.5
#2 b            6.5

```

---

Or using `data.table` by specifying the `.SDcols` and `setnames`

```
compute_price_mean <- function(DT, colname1, p, t) {
     setnames(DT[, mean(.SD[[1]]), by = t, .SDcols = p], "V1", colname1)[]
 }
#    type mean_price
#1:    a        2.5
#2:    b        6.5      

```