首页 > 解决方案 > 有没有办法在 R 中折叠加权平均值?

问题描述

我正在尝试将以下代码从 Stata 转换为 R:

collapse (mean) erate_total_male laborforce_male erate_total_male_1953 laborforce_male_1953 share_expellees_male share_dest_flats instrument share_agric_1939 city_state (max) occzone_occu [aw=laborforce_male], by(bundesland_id_1953 occupation_id)

我试图collapse在 R 中使用该包,但我不确定如何合并 Stata 代码的权重元素或最大值(尽管我可能只是生成一个新变量来解决这个问题)。

test1 <- rep_data %>%
  mutate(bundesland_id_1953 = 
           case_when(
             bundesland_id == 8 ~ 99,
             bundesland_id == 9 ~ 99,
             bundesland_id == 10 ~ 99,
           )) %>%
  group_by(bundesland_id_1953, occupation_id) %>% 
  select(erate_total_male, laborforce_male, erate_total_male_1953, laborforce_male_1953, share_expellees_male, share_dest_flats, instrument_male, share_agric_1939, city_state, occzone_occu) %>% fmean

我还尝试为所有变量生成均值,但是在添加权重时遇到了同样的问题:

t6Data2 <- rep_data %>%
  mutate(bundesland_id_1953 = 
           case_when(
             bundesland_id == 8 ~ 99,
             bundesland_id == 9 ~ 99,
             bundesland_id == 10 ~ 99,
           )) %>% 
  group_by(bundesland_id_1953, occupation_id) %>% summarise_at(vars(erate_total_male, laborforce_male, erate_total_male_1953, laborforce_male_1953, share_expellees_male, share_dest_flats, instrument_male, share_agric_1939, city_state)

最后,我尝试了一个循环,但是当我使用 lm() 运行回归时,我的变量没有出现:

test444 <- rep_data %>%
  mutate(bundesland_id_1953 = 
           case_when(
             bundesland_id == 8 ~ 99,
             bundesland_id == 9 ~ 99,
             bundesland_id == 10 ~ 99,
           )) %>% 
  group_by(bundesland_id_1953, occupation_id)

t6_data_test4 <- sapply(c(test444$erate_total_male, test444$laborforce_male, test444$erate_total_male_1953, test444$laborforce_male_1953, test444$share_expellees_male, test444$share_dest_flats, test444$instrument_male, test444$share_agric_1939, test444$city_state), function(x) {
  weighted.mean(x, weight = laborforce_male)
}) 

我不知道该怎么做,但我会很感激任何帮助。我是一个相对新手,所以对于我在代码中犯的任何明显错误,我深表歉意。

标签: rstatameancollapseweighted

解决方案


这有效:

library(dplyr)

d <- tibble::tibble(
  bundesland_id_1953 = sample(letters[1:3], 100, replace = TRUE),
  occupation_id = factor(sample(1:3, 100, replace = TRUE)),
  x = sample(1:5, 100, replace = TRUE),
  y = sample(1:5, 100, replace = TRUE),
  weight = runif(100)
)

d <- group_by(d, bundesland_id_1953, occupation_id)

bind_cols(
  group_keys(d),
  group_split(d) %>% 
    purrr::map_df(
      # [NOTE] use `across` in forthcoming dplyr 1.0.0
      ~ summarise_at(.x, vars(x, y), weighted.mean, w = .x$weight)
    )
)

我对下面的解决方案不满意,因为它比“整洁”工具要提供的更难看。该死的,它比 Stata 更易读——我对自己很失望。

我也怀疑你的加权方案:在某些时候,看起来你是通过……本身来加权一个变量?但我当然不知道数据。


推荐阅读