2

I am a new user to R and I want to recall a block of code for different variables and I want to do something like this:

   myfunc<- function(dat, groupvar, interestvar){
      a<- dat%>% group_by(groupvar) %>% summarize(m=mean(interestvar))
         ..... other codes ....
      return(a)   }

myfunc(data=newdata, groupvar=variable1, interestvar=variable3)
myfunc(data=newdata, groupvar=variable2, interestvar=varaible4)

Here the variable1-vari all are variables inside newdata. It seems if I call intrestvar=newdata$varaible3, that part will work. However, the way I call groupvar still don't tell the function the group by is done by variable1. How do I make it work?

Ronak Shah
  • 286,338
  • 16
  • 97
  • 143
lydia
  • 31
  • 2

1 Answers1

2

You can use curly-curly operator ({{}}) from rlang to pass unquoted variable in the function.

library(dplyr)
library(rlang)

myfunc<- function(dat, groupvar, interestvar){
  a<- dat%>% group_by({{groupvar}}) %>% summarize(m=mean({{interestvar}}))
  return(a)   
}

myfunc(dat =mtcars, groupvar=cyl, interestvar=mpg)
#   cyl        m
#  <dbl>    <dbl>
#1     4 26.66364
#2     6 19.74286
#3     8 15.1    

myfunc(dat = mtcars, groupvar=am, interestvar=disp)
#     am        m
#  <dbl>    <dbl>
#1     0 290.3789
#2     1 143.5308
Ronak Shah
  • 286,338
  • 16
  • 97
  • 143
  • Thanks. the curly bracket works. But I got more questions if I add few more lines: a% group_by(groupvar) %>% summarise(q3=quantile({{interestVar1}}, probs=0.75, type=1), q1=quantile({{interestVar1}}, probs=0.25, type=1))%>% mutate(iqr=(q3-q1), lowerbound=q1 -1.5*iqr , upperbound=q3 +1.5*iqr) %>% select(year_month_sort_key, lowerbound, upperbound) } It gave me error and said the groupvar1 is not found in iqr. Also, I couldn't call iqr, (or if I use return(dat2) and I could not call it either.Sorry for asking basic questions. – lydia Aug 17 '20 at 13:16
  • Perhaps, it is better to ask that as a new question as this information was not shared in the original question. – Ronak Shah Aug 17 '20 at 13:22
  • I had posted a new question with the title "How do write blocks of codes into functions in Rstudio like in SAS macros" as you suggested. Thanks – lydia Aug 17 '20 at 13:56
  • Thanks so you can accept this answer by clicking on check mark next to vote button so that it can be marked as solved. – Ronak Shah Aug 17 '20 at 13:59
  • @lydia Please accept the answers before asking new questions. Read https://stackoverflow.com/help/someone-answers – Ronak Shah Aug 21 '20 at 03:03