如何按 R 中的列表中的组获取​​平均值

How can I get the mean by groups in a list in R

我有一个这样的列表:

Years sallary
1 121
12 4343
25 1341
23 12
15 325
2 574
4 5473
8 347
30 352
29 237
3 734
10 2469
11 1239
5 2456
20 231
6 9381
28 1284
13 1295
9 129
7 931
19 1293
27 1239
14 124
24 512
18 912
26 8321
17 12383
22 419
16 129
more than 30 years 12394
21 1239

抱歉,名单太大了,但我的名单更大,我必须确保没有人给我硬编码的名单。 我想要的是一个包含分组年份平均值的列表。


group1 <- c("less than 1 year", "1", "2", "3", "4", "5")
group2 <- c("6", "7", "8", "9", "10")
...

| Years | sallary | 
|:---- |:------:| 
| group1  | e.g. 1295    | 
| group2  | e.g. 12012   | 
| group3  | e.g. 8521    | 
| group4  | e.g. 2491    | 
| group5  | e.g. 12349   | 
| group6  | e.g. 1299    | 

I amm sorry for this list but otherwise it gives me an error if I do not put the table inside the code block... But that is the list I want.

其他答案没有帮助,因为它们是按相同的行计算平均值的。但是我有一个字符串。

感谢您的指点。

我们根据组向量替换'Years'。将所有 'group' 向量放入 listmget,将 list 转换为两列 data.frame (stack),然后执行加入原始数据,将 'Years' 列替换为 'value',将其用作分组列,并将 summarise 替换为 'sallary' 列

library(dplyr)
df2 <- stack(mget(ls(pattern = '^group\d+$')))[2:1]
names(df2)[2] <- 'Years'
df1 %>% 
     left_join(df2, by = 'Years') %>%
     group_by(Years = ind) %>%
     summarise(sallary = mean(sallary, na.rm = TRUE))