简体   繁体   中英

R: Passing function argument to sqldf

I've seen a similar question here and example 5 here but i can't get my example to work. I'm not very experienced in R so maybe it's something silly. I just want to have a function that the argument is a column name used by sqldf

My best guess:

function1 <- function(x) {
    ranking_test <<- sqldf ('select $x from lat_lon_combo t1')
}

function1(t1.lat_lon)

results in

"Error in mget(words, envir, "any", NA, inherits = TRUE) : object 't1.lat_lon' not found"

Although it t1.lat_lon should exist. Any ideas?

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):

  1. 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") 
  2. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM