tall_table
tall_table

Reputation: 311

Why dplyr group_by, summarise, and weighted mean is throwing an error

I am running into a (new since updating R and other packages) error when trying to calulated weighted means of a grouped variable. Reproducible example is below. This used to work fine but now something seems to have changed. I get the following error:

Error: Problem with summarise() input avg. x 'x' and 'w' must have the same length ℹ Input avg is weighted.mean(outcome, na.rm = T, w = df$wt). ℹ The error occurred in group 1: groups = "A".

# Reprex

library(dplyr)

# Data
df <- data.frame(
  groups = rep(c("A", "B", "C"), each = 10),
  outcome = rnorm(30),
  weight = rnorm(30))

# This Works
df %>%
  group_by(groups) %>%
  summarise(avg = mean(outcome, na.rm = T))

# This throws an error
df %>%
  group_by(groups) %>%
  summarise(w_avg = weighted.mean(outcome, na.rm = T, w = df$weight))

Upvotes: 0

Views: 346

Answers (1)

Liman
Liman

Reputation: 1300

Try this:

# This throws an error
df %>%
    group_by(groups) %>%
    summarise(w_avg = weighted.mean(outcome, na.rm = T, w = weight))

Upvotes: 1

Related Questions