对于示例中的简单整形,您可以简单地aggregate
在 base R 中使用,它可以执行您想要的操作,而无需指定列名:
aggregate(carb~cyl+hp, mtcars, FUN=mean)
cyl hp carb
1 4 52 2
2 4 62 2
3 4 65 1
4 4 66 1
5 4 91 2
.....
或在所有列上:
aggregate(.~cyl+hp, mtcars, FUN=mean)
cyl hp mpg disp drat wt qsec vs am gear carb
1 4 52 30.40000 75.7000 4.930000 1.615000 18.52000 1.0000000 1.0000000 4.000000 2
2 4 62 24.40000 146.7000 3.690000 3.190000 20.00000 1.0000000 0.0000000 4.000000 2
3 4 65 33.90000 71.1000 4.220000 1.835000 19.90000 1.0000000 1.0000000 4.000000 1
4 4 66 29.85000 78.8500 4.080000 2.067500 19.18500 1.0000000 1.0000000 4.000000 1
5 4 91 26.00000 120.3000 4.430000 2.140000 16.70000 0.0000000 1.0000000 5.000000 2
.....