1

I am trying to write a function that summarises two metrics based on Sepal.Length and Sepal.Year, this was my attempt. Am I going about it the wrong way?

df = structure(list(Sepal.Length = c("short","short", "long", "short"),
Sepal.Width = c("wide", "narrow", "wide", "narrow"), 
Petal.Length = c(1.4, 1.8, 1.3, 1.5), 
Petal.Width = c(0.4, 0.7, 0.5, 0.2),                                                                                                             
Species = structure(c(1L, 1L, 1L, 1L), 
.Label = c("setosa","versicolor", "virginica"), class = "factor")),
.Names = c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width", "Species"),                                                                                                                                                                                                
row.names = c(NA, 4L), class = "data.frame")                                                                                                                                                                                                                                                            

mysummary <- function(df, Criteria1, Criteria2, Metric1, Metric2){
    df %>%
        group_by(.dots=c(Criteria1,Criteria2)) %>%
        summarise_each(funs(mean, n()),Metric1,Metric2) %>%
        filter(paste(Metric1,"_n") > 3) %>%
        arrange(desc(paste(Metric1,"_mean")))}

mysummary(df,"Sepal.Length","Sepal.Width","Petal.Length","Petal.Width")

The results would be: Short Wide 1.4 0.4 Short Narrow 1.65 0.45 Long Wide 1.3 0.5

timnus
  • 197
  • 10
  • can you provide a minimal working example and your desired result? – Cettt Aug 29 '18 at 06:48
  • 1
    Welcome to SO. Please provide sample data in a copy&paste-able format (e.g. using dput). It might be useful to take a look at how to provide [a minimal reproducible example.][1] [1]: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – thothal Aug 29 '18 at 06:48
  • See my answer [here](https://stackoverflow.com/questions/52057952/how-to-paste-subset-of-columns-using-dplyr/52058521#52058521), also you can check [Programming with dplyr](https://cran.r-project.org/web/packages/dplyr/vignettes/programming.html) – A. Suliman Aug 29 '18 at 07:56
  • @Cettt I have now updated it, thanks! – timnus Aug 29 '18 at 08:12

1 Answers1

1

You can find the conditional mean using the below code

result <- summarise(group_by(Df_name,c("Year","Name")), Metric1_mean=mean(Metric1),Metric2_mean = mean(Metric2))
Hunaidkhan
  • 1,411
  • 2
  • 11
  • 21