0

I have a dataset like this: enter image description here

I want to write a basic function like this:

basicStat<-function(recentdata, interestvar="inventory ", groupvar="indoor_size_cat", interestindvar="indoor_size" ){

interestvar<-enquo(interestvar)

groupvar<-enquo(groupvar)

interestindvar<-enquo(interestindvar)

statRecent<-data %>%

  group_by(!!groupvar) %>%

  summarise(q3=quantile(interestVar, probs=0.75, type=1),

            q1=quantile(!!as.symbol(interestVar), probs=0.25, type=1),

            sd=sd(!!as.symbol(interestVar)),

            mu=mean(!!as.symbol(interestVar))) %>%

  mutate(iqr=(q3-q1), lowerbound=max(0,q1 -1.5*iqr) , upperbound=q3 +1.5*iqr,

         cv=sd/mu) %>%

  select( !!as.symbol(groupvar), lowerbound, upperbound, cv, sd, mu)

return(statRecent)

}

it give me errors:

Error in UseMethod("group_by_") : no applicable method for 'group_by_' applied to an object of class "function".

How can I fix it? thanks

r

lydia
  • 31
  • 1
  • 3
  • 1
    Please don't add data as images use `dput` to share them. Read how to give a [reproducible example](http://stackoverflow.com/questions/5963269). – Ronak Shah Aug 21 '20 at 03:01

1 Answers1

0

If you want to pass column data as string variables I think something like this should work.

library(dplyr)
library(rlang)

basicStat<-function(recentdata, interestvar="inventory", 
                      groupvar="indoor_size_cat", interestindvar="indoor_size" ){

  interestvar <- sym(interestvar)
  groupvar <- sym(groupvar)
  interestindvar <- sym(interestindvar)
  
  statRecent<- recentdata %>%
    group_by(!!groupvar) %>%
    summarise(q3=quantile(!!interestVar, probs=0.75, type=1),
              q1=quantile(!!interestvar, probs=0.25, type=1),
              sd=sd(!!interestVar),
              mu=mean(!!interestVar)) %>%
    mutate(iqr=(q3-q1), lowerbound = max(0,q1 -1.5*iqr) , 
           upperbound=q3 +1.5*iqr, cv=sd/mu) %>%
    select( !!groupvar, lowerbound, upperbound, cv, sd, mu)
  return(statRecent)
}

basicStat(data)
#Or calling it explicitly
#basicStat(data, "inventory", "indoor_size_cat", "indoor_size")

You have passed interestindvar in the function but not used it anywhere.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • I tried with this but it give me an error as :Error in splice(dot_call(capture_dots, frame_env = frame_env, named = named, : object 'interestVar' not found – lydia Aug 21 '20 at 18:41
  • @lydia How are you calling `basicStat` function? – Ronak Shah Aug 22 '20 at 00:17