Issues regarding the command by and weighted.mean already exist but none was able to help solving my problem. I am new to R and am more used to dat
Try using the dplyr package as follows:
df <- read.table(text = 'obs income education weight
1 1000 A 10
2 2000 B 1
3 1500 B 5
4 2000 A 2',
header = TRUE)
library(dplyr)
df_summary <-
df %>%
group_by(education) %>%
summarise(weighted_income = weighted.mean(income, weight))
df_summary
# education weighted_income
# A 1166.667
# B 1583.333
df_final <- left_join(df, df_summary, by = 'education')
df_final
# obs income education weight weighted_income
# 1 1000 A 10 1166.667
# 2 2000 B 1 1583.333
# 3 1500 B 5 1583.333
# 4 2000 A 2 1166.667