3

I strictly need to use the summarise_at to compute a weighted mean, with weights based on the values of another column

    df %>% summarise_at(.vars = vars(FACTOR,tv:`smart tv/console`), 
                  .funs = weighted.mean, w=INVESTMENT, na.rm=TRUE)

It always shows the error: 'INVESTMENT' is not found.

I then tried with:

df %>%summarise_at(.vars = vars(FACTOR,tv:`smart tv/console`), 
               .funs = weighted.mean, w=vars(INVESTMENT), na.rm=TRUE)

But in this case : Evaluation error: 'x' and 'w' must have the same length.

Why is this? Am I doing anything wrong? Do you have hints to solve this issue? Thanks

3nomis
  • 531
  • 6
  • 17

1 Answers1

2

You can specify the weights directly within the weighted.mean() function, within the call to funs() like so:

data.frame(x=rnorm(100), y=rnorm(100), weight=runif(100)) %>%
      summarise_at(vars(x,y), funs(weighted.mean(., w=weight)))
mmk
  • 121
  • 2
  • `summarise_at` has now been superseded by `across`. Your example code may now look something like this: `data.frame(x=rnorm(100), y=rnorm(100), weight=runif(100)) %>% summarise(across(x:y, ~weighted.mean(., w = weight)))` – JPD Sep 23 '20 at 08:15