How to name a column in summarise based on input to function

I am still finding my way around tidy evaluation. One thing I struggle with is using the name passed into a function on the left hand side of a dplyr verb. Please can someone help on the basis of the example.
feel free to offer other improvements to style!

In the below, the mean passed back will always be in a column called outputcol. how do I change the below to pass it back using the same name as the column passed in (mass in the example)

# create a table of frequency of a category column as a percentage
# with optional summary of another column by named function

percentagetable <- function(df, category, summaryvar = NULL, summaryfunc = NULL) {
  quocategory <- enquo(category)
  
  hassummary <- !missing(summaryvar) & !missing(summaryfunc)
  
  if (hassummary) {
    quosummaryvar <- enquo(summaryvar)
    summaryvarname <- quo_name(quosummaryvar)
    outputsym <- rlang::ensym(summaryvarname)
  }
  
  dfout <- df %>%
    group_by(!!quocategory)
  
  if (hassummary) {
    dfout <- dfout%>%
      summarise (percent = 100 * n() / nrow(df), outputcol = summaryfunc(!!quosummaryvar)) 
  } else {
    dfout <- dfout %>%
      summarise (percent = 100 * n() / nrow(df)) 
  }
  

  dfout
}

speciessummary <- percentagetable(starwars, species, mass, mean)

print(speciessummary)

I did more research (having given up before). I didn't realise !! would work
I changed the longer summarise

summarise (percent = 100 * n() / nrow(df), !!summaryvarname := summaryfunc(!!quosummaryvar))

Now what I would really like is to somehow combine the 2 summarise so that the expression <!!summaryvarname := summaryfunc(!!quosummaryvar)> evaluates to nothing if summaryvar is missing

You might be able to use 'curly-curly' for some of those.

Thanks. I think I tried that. I have been able to use curly curly in the past (but only once) on the right hand of LH = RH in a dplyr function. But didn't seem to be the right thing for LH. I suspect I need to go back to basics and get to grips with this stuff

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.