Rstudyer
Rstudyer

Reputation: 477

Passing variable name to function

I am writing a function to do the similar task. Frist, I wrote it without function. The non-function code is like:

df<-rio::import("avenir_allvariable_5.csv")%>%
      filter(definition=="") %>%
      select(variable, definition, label, termType)
kbl(df, desc=T)%>%
    kable_classic(full_width=F, html_font = "Cambria")

this one works. And now i want to write a function only replace one variable: definition. For the rest variable, I keep their name there bc I do not need change them every time. So my code is like:

na_check<-function(var){
    dfck<-rio::import("avenir_allvariable_5.csv")%>%
      filter(var=="") %>%
      select(variable, var, label, termType)
kbl(dfck, desc=T)%>%
    kable_classic(full_width=F, html_font = "Cambria")
}

na_check("definition")

But it cannot spit out the result as non-function code I wrote above.It returns nothing result compared to the non-function code which should be 1 qualified query result. Could anyone help to figure out what wrong is it? Thanks a lot~~!

Upvotes: 0

Views: 49

Answers (1)

akrun
akrun

Reputation: 887751

Convert to symbol and evaluate (!!)

na_check<-function(var){
    dfck<-rio::import("avenir_allvariable_5.csv")%>%
      filter(!! rlang::ensym(var)=="") %>%
      select(variable, all_of(var), label, termType)
kbl(dfck, desc=TRUE)%>%
    kable_classic(full_width=FALSE, html_font = "Cambria")
}

-testing

na_check("definition")

Or another option is to make use of if_all/if_any/across (as it is a single column, it doesn't matter which function is used)

na_check<-function(var){
    dfck<-rio::import("avenir_allvariable_5.csv")%>%
      filter(if_all(all_of(var), ~ .x =="")) %>%
      select(variable, all_of(var), label, termType)
kbl(dfck, desc=TRUE)%>%
    kable_classic(full_width=FALSE, html_font = "Cambria")
}

Upvotes: 1

Related Questions