0

I have a datfarame as shown below

enter image description here

I want to calculate mean of each column for each group based on A-Block and A-District. Output will be as below

enter image description here

I tried summarize function from tidyverse but it is giving mean of all columns.

How we can do it using tidyverse or dplyr??

How this can be achieved using tidyverse or dplyr??

gis.rajan
  • 517
  • 3
  • 20
  • So you want mean for Kumarkhand, but sum for Other? Also it's better if you share the code of your dataset directly in the question. You can use `dput` to do so. – Maël Jan 10 '23 at 09:24
  • There will be two groups based on A-Block, and A-District and for each group, there will be a mean value for May 22, June 22, and so on as shown in the example. I am also sharing the sample dataset. https://docs.google.com/spreadsheets/d/1-9R4boxzhzueu79MDyr0gfcPljWNGq40/edit?usp=sharing&ouid=114652882170449489723&rtpof=true&sd=true – gis.rajan Jan 10 '23 at 09:32
  • 1
    `df %>% group_by(A.Block, A.District) %>% summarise(across(!c(A.Block, A.District), mean))` - in fact you can probably use `across(everything(), mean)` since I believe it automatically avoids selecting grouping variables. – Paul Stafford Allen Jan 10 '23 at 09:45
  • @Paul Yes you are right, I find about across function from this linkhttps://stackoverflow.com/questions/29083641/rowmeans-function-in-dplyr. – gis.rajan Jan 10 '23 at 10:48
  • my code `mds = ds %>% group_by(c_plot_gps, c_plot_gp_1) %>% summarise(across(where(is.numeric), ~ mean(.x, na.rm = TRUE)))` – gis.rajan Jan 10 '23 at 10:52

1 Answers1

-1

Use group_by function.

df %>% 
  group_by(A.Block, A.District) %>%
  summarise(mean_May_22 = mean(May_22))
npetrov937
  • 158
  • 7