1

I have a function that I wrote which is supposed to filter some values and then produce a crosstabulation. It filters the values using the dplyr filter,select commands.

My problem is that when I pass the name of the column ot the function I get an error, and when I pass the name as string with "" around it, it does not filter the observations. Here is the code:

fnDoCrosstab <- function(a) {
  x <- surv_data1 %>% filter(a != "blank") %>% select(a) %>% as.matrix() %>% as.vector()
  y <- surv_data1 %>% filter(a != "blank") %>% select(segment_name) %>% as.matrix() %>% as.vector()
  CrossTable(x,y, format = "SPSS",prop.chisq = F)
}
fnDoCrosstab(b_thisyear)
Corel
  • 581
  • 3
  • 21
  • 1
    Suggested dupe: [dplyr mutate with variable column names](https://stackoverflow.com/q/26003574/903061) – Gregor Thomas Jun 20 '17 at 23:49
  • 1
    Also note that `dplyr` comes [with a vignette on Programming with dplyr](https://cran.r-project.org/web/packages/dplyr/vignettes/programming.html) which covers how to do this in detail. – Gregor Thomas Jun 20 '17 at 23:50

1 Answers1

2

With the latest version of dplyr (0.7), you can do something like this

library(dplyr)

fnDoCrosstab <- function(a) {
  a <- enquo(a)
  x <- mtcars %>% filter((!!a) != 0) %>% select(mpg, !!a) %>% as.vector()
  x
}
fnDoCrosstab(am)
fnDoCrosstab(vs)

You capture the unevaluated field name with enquo() and then you expand that as necessary with !!

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • That worked! Although I'm not sure why. What does `enquo()` actually do? And what is the `!!` operator? – Corel Jun 21 '17 at 00:10
  • There is all new stuff that `dplyr` (and more specifically `rlang`) has introduced. To learn how to use them read the [programming with dplyr vignette](https://cran.r-project.org/web/packages/dplyr/vignettes/programming.html) – MrFlick Jun 21 '17 at 00:19
  • I try to reproduce the same thing with mutate function, but it is not working, do you have an idea why ? `df <- df %>% filter((!!originalvar) > 1) %>% mutate( (!!originalvar) = 99)` – M4hd1 Jul 03 '18 at 13:54
  • 1
    @M4hd1 if you want to expand on the left side of an equals in mutate, you need to use `:=` rather than `=`. try `mutate( (!!originalvar) := 99)` – MrFlick Jul 03 '18 at 14:23
  • @MrFlick Thank you ! – M4hd1 Jul 03 '18 at 14:30