【发布时间】:2021-12-24 12:11:32
【问题描述】:
如何在 data.farme 的不同级别聚合。
示例:
数据:
> dput(sampledata)
structure(list(city = c("a", "a", "b", "b", "c", "c"), workerID = c("1",
"2", "3", "4", "5", "6"), salary = c(50000, 1e+05, 60000, 3e+05,
40000, 80000)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-6L))
解决方案:
left_join(sampledata,
sampledata %>%
group_by(city) %>%
summarise(city_level_mean = mean(salary)))
输出:
Joining, by = "city"
# A tibble: 6 × 4
city workerID salary city_level_mean
<chr> <chr> <dbl> <dbl>
1 a 1 50000 75000
2 a 2 100000 75000
3 b 3 60000 180000
4 b 4 300000 180000
5 c 5 40000 60000
6 c 6 80000 60000
还有其他解决方案吗?
【问题讨论】:
-
merge(sampledata,aggregate(cbind(city_level_mean=salary)~city,data=sampledata,mean),by="city") -
@camille 我同意你的看法