简体   繁体   English

R:将函数参数传递给sqldf

[英]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. 我在这里看到了一个类似的问题, 这里有 例子5,但是我无法让我的例子工作。 I'm not very experienced in R so maybe it's something silly. 我对R不是很有经验,所以也许是傻事。 I just want to have a function that the argument is a column name used by sqldf 我只想要一个函数,该参数是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" “mget中出错(words,envir,”any“,NA,inherits = TRUE):找不到对象't1.lat_lon'

Although it t1.lat_lon should exist. 虽然它应该存在t1.lat_lon。 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. 列名称 t1.lat_lon可能存在,但在调用function1 ,您引用的是名为t1.lat_lon变量 ,该变量不存在。

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. 将其作为字符串传递,并使用pastesprintf来形成查询字符串。 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). 这种类型的解除引用在执行诸如plot(disp ~ mpg, data = mtcars)类的事情时使用(并且很有用)(尽管这对于公式来说甚至略有不同)。 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. 顺便说一句:在这两种情况下,我都会返回从sqldf返回的值,我选择(我强烈要求) 反对副作用,就像你在函数中所做的那样。 Side effects can be desired but, if avoidable, are opined to provide cleaner and more predictable functions. 可能需要副作用,但如果可以避免,则可以提供更清晰和更可预测的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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