msheffer msheffer - 2 years ago 107
R Question

'Not Found' Error for weight trying to calculate weighted average with dplyr summarize_all

I'm trying to calculate a weighted mean using dplyr and summarize_all. I've seen similar questions, most specifically this post:
How do I compute weighted average using summarise_each?


This seems pretty straight-forward but I keep getting an object 'weight' not found error message.

Here's a reproducible example:

data <- tibble::tribble(~group, ~weight, ~x1, ~x2,
1, 1, 3, 2,
1, 1, 4, 7,
1, 1, 1, 4,
2, 1, 2, 2,
2, 1, 5, 3,
2, 1, 4, 2)

# Just regular means
data %>%
dplyr::group_by(group) %>%
dplyr::summarize_all(mean)

# First attempt
data %>%
dplyr::group_by(group) %>%
dplyr::summarize_all(weighted.mean(., weight))

# Second attempt based on syntax from post above
data %>%
dplyr::group_by(group) %>%
dplyr::summarize_all(funs(weighted.mean(., weight)), -weight)


This is what happens when I run this code:

> data %>%
+ dplyr::group_by(group) %>%
+ dplyr::summarize_all(mean)
# A tibble: 2 x 4
group weight x1 x2
<dbl> <dbl> <dbl> <dbl>
1 1 1 2.666667 4.333333
2 2 1 3.666667 2.333333
>
> data %>%
+ dplyr::group_by(group) %>%
+ dplyr::summarize_all(weighted.mean(., weight))
Error in weighted.mean.default(., weight) : object 'weight' not found
>
> data %>%
+ dplyr::group_by(group) %>%
+ dplyr::summarize_all(funs(weighted.mean(., weight)), -weight)
Error in eval_bare(dot$expr, dot$env) : object 'weight' not found


Any information on why this is happening and what, if anything, I can do about it, is greatly appreciated.

Thanks!

Answer Source

The problem is that by using summarize_all you're trying to also calculate the weighted mean for the weight column.

You're likely to be more interested in summarise_at:

data %>%
  dplyr::group_by(group) %>%
  dplyr::summarize_at(vars(x1, x2), funs(weighted.mean(., weight)))

# A tibble: 2 x 3
  group       x1       x2
  <dbl>    <dbl>    <dbl>
1     1 2.666667 4.333333
2     2 3.666667 2.333333
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download