Use below steps:
get the columns as list
remove the columns needs to be aggregated from the columns list.
apply groupBy & agg.
**Ex**:
val seq = Seq((101, "abc", 24), (102, "cde", 24), (103, "efg", 22), (104, "ghi", 21), (105, "ijk", 20), (106, "klm", 19), (107, "mno", 18), (108, "pqr", 18), (109, "rst", 26), (110, "tuv", 27), (111, "pqr", 18), (112, "rst", 28), (113, "tuv", 29))
val df = sc.parallelize(seq).toDF("id", "name", "age")
val colsList = df.columns.toList
(colsList: List[String] = List(id, name, age))
val groupByColumns = colsList.slice(0, colsList.size-1)
(groupByColumns: List[String] = List(id, name))
val aggColumn = colsList.last
(aggColumn: String = age)
df.groupBy(groupByColumns.head, groupByColumns.tail:_*).agg(avg(aggColumn)).show
+---+----+--------+
| id|name|avg(age)|
+---+----+--------+
|105| ijk| 20.0|
|108| pqr| 18.0|
|112| rst| 28.0|
|104| ghi| 21.0|
|111| pqr| 18.0|
|113| tuv| 29.0|
|106| klm| 19.0|
|102| cde| 24.0|
|107| mno| 18.0|
|101| abc| 24.0|
|103| efg| 22.0|
|110| tuv| 27.0|
|109| rst| 26.0|
+---+----+--------+