Common mistake. The column name t1.lat_lon
may exist, but in your call to function1
, you are referencing a variable named t1.lat_lon
, which does not exist.
You have a couple of options, and for simplicity I recommend the first (strings):
Pass it as a string, and use paste
or sprintf
to form the query string. Such as:
library(sqldf)
func1 <- function(x) {
sqldf(sprintf("select %s from mtcars where cyl > 7", x))
}
func1("disp")
If you really must reference it without the quotes, you can do this trickery, but in this case it is unnecessary complexity (for the sake of two quotation mark symbols):
func2 <- function(x) {
sqldf(sprintf("select %s from mtcars where cyl > 7",
deparse(substitute(x))))
}
func2(disp)
This type of dereferencing is used (and useful) when doing something like plot(disp ~ mpg, data = mtcars)
(though that does things even slightly differently with a formula). In those situations it adds usefulness at the expense of some code complexity and indirection. If you don't need this (and, based on your example, it does not look like you do), then I would avoid this for the sake of simplicity.
BTW: in both cases, I return the value returned from sqldf
, I chose (and I strongly urge) against side-effects as you did in your function. Side effects can be desired but, if avoidable, are opined to provide cleaner and more predictable functions.