Reputation: 633
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)
Upvotes: 1
Views: 1136
Reputation: 206167
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 !!
Upvotes: 2