If you more than one group to recode you could something like:
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
df1 <- tibble::tribble(
~Codes, ~n, ~ ave,
1, 25, 80,
2, 10, 75,
3, 15, 65,
4, 25, 80,
5, 30, 90,
6, 30, 85,
7, 40, 75,
8, 60, 70,
9, 10, 80
)
df2 <- df1 %>%
mutate(Codes2 = case_when(
Codes %in% c(4,5,6) ~ 11 ,
# optionally more recodings
# others remain the same
TRUE ~ Codes
),
nave = n * ave
) %>%
group_by(Codes2) %>%
summarise(n=sum(n), nave=sum(nave)) %>%
rename(Codes=Codes2) %>%
mutate (ave = nave / n) %>%
select(-c(n,nave))
print(df2)
#> # A tibble: 7 x 2
#> Codes ave
#> <dbl> <dbl>
#> 1 1 80
#> 2 2 75
#> 3 3 65
#> 4 7 75
#> 5 8 70
#> 6 9 80
#> 7 11 85.3
Created on 2021-12-02 by the reprex package (v2.0.1)