Home > other >  Multiple Group - Weighted mean - not working in r (using dplyr)
Multiple Group - Weighted mean - not working in r (using dplyr)

Time:10-30

I am trying to obtain the weighted mean of some soil properties, weighted by their surface but aggregated by their owner and other levels. My dataset looks like this full_dataset and i would like to obtain the mean like thismean_dataset. My code right now is:

results<- original_df %>% 
group_by(owner,cultivar) %>%                
summarise(across(.cols= where(is.numeric),fns= weighted.mean(.,w= surface)))

but at the moment is not working, because the output as the same number of rows of the original dataset. What am I missing?

data:

structure(list(town = c("a", "a", "a", "a", "b", "b", "b", "b", 
"b", "C", "C", "C", "C", "C", "C"), cultivar = c(1L, 1L, 2L, 
2L, 1L, 2L, 3L, 4L, 4L, 3L, 3L, 2L, 2L, 1L, 1L), owner = c("A", 
"A", "B", "C", "A", "B", "B", "C", "C", "B", "B", "C", "C", "A", 
"A"), surface = c(456L, 446L, 462L, 120L, 204L, 250L, 642L, 466L, 
580L, 258L, 146L, 617L, 79L, 304L, 48L), x1 = c(202L, 647L, 525L, 
536L, 563L, 269L, 376L, 492L, 229L, 177L, 413L, 156L, 77L, 79L, 
609L), x2 = c(91L, 334L, 110L, 533L, 161L, 605L, 344L, 380L, 
221L, 368L, 179L, 531L, 357L, 66L, 157L), x3 = c(300L, 90L, 570L, 
43L, 403L, 245L, 640L, 344L, 371L, 70L, 546L, 400L, 255L, 176L, 
336L)), class = "data.frame", row.names = c(NA, -15L))

CodePudding user response:

If we use ., we need the lambda (~) i..e. the ~ is equivalent to function(.).

library(dplyr)
original_df %>% 
 group_by(owner,cultivar) %>%                
  dplyr::summarise(across(.cols= starts_with('x'),
     ~ weighted.mean(.,w= surface)), .groups = 'drop')

This may also work by just removing the () and the . as the w is already specified as 'surface' and thus it implicitly take the x column looped

original_df %>% 
 group_by(owner,cultivar) %>%                
 dplyr::summarise(across(.cols= starts_with('x'),
     weighted.mean, w= surface), .groups = 'drop')

-output

# A tibble: 5 × 5
  owner cultivar    x1    x2    x3
  <chr>    <int> <dbl> <dbl> <dbl>
1 A            1  376.  172.  226.
2 B            2  435.  284.  456.
3 B            3  332.  327.  486.
4 C            2  204.  514.  333.
5 C            4  346.  292.  359.
  • Related