I am trying to write a function that uses dplyr to count up all unique values of z. My function works fine when I have the variable actually named z. However, if the variable is named x, I get an error (below code).
test.data<-data.frame(y=c(1:10),
x=c(letters[1:10]))
test.data$x<-as.character(test.data$x)
obsfunction<-function(z,y,data){
filter_(data,
!is.na(deparse(substitute(y))))%>%
distinct_(., deparse(substitute(z)))%>% #the line that breaks it
count_(.)
}
obsfunction(z=x,y,data=test.data)
So, the above code doesn't work and gives this error:
>Error in eval(substitute(expr), envir, enclos) : unknown column 'z'
Changing z to x in the function (or renaming x as z) makes it work, but I don't want to have to rename everything, especially considering y works with different names.
I have tried lazyeval::interp and quote() per the vignette, this question, and this question.
distinct_(lazyeval::interp(as.name(z)))%>%
>Error in as.name(z) : object 'x' not found
distinct_(quote(z))%>%
>Error in eval(substitute(expr), envir, enclos) : unknown column 'z'
What am I missing? How do I get z to accept x as the column name?