使用名称中包含下划线的r变量的sqldf

使用名称中包含下划线的r变量的sqldf,r,naming-conventions,sqldf,R,Naming Conventions,Sqldf,此代码 > A <- data.frame(col1 = c(1,2,3),col2 = c("red","blue","green")) > color_num <- 2 > fn$sqldf("select * from A where col1 >= '$color_num'") >A color\u num fn$sqldf(“从where col1>='$color\u num'中选择*) 产生错误 eval(parse(text=paste(…

此代码

> A <- data.frame(col1 = c(1,2,3),col2 = c("red","blue","green"))
> color_num <- 2
> fn$sqldf("select * from A where col1 >= '$color_num'")
>A color\u num fn$sqldf(“从where col1>='$color\u num'中选择*)
产生错误

eval(parse(text=paste(…,sep=”“)中出错),env:object 找不到“颜色”

但是,如果变量
color\u num
的名称没有下划线(比如
colornum
),则执行
fn$sqldf(“select*from a where col1>='$colornum')
会产生预期的结果,不会出现错误

我认为
sqldf
在幕后用句点替换下划线,导致它将下划线前面的组件视为表,将下划线后面的部分视为列名。(和评论)对于
sqldf
中有关列名的问题,表示该库曾经用下划线替换过点,但现在不再使用,但我找不到任何关于用点替换下划线的信息

这是一个问题,因为我使用的命名约定大量使用下划线作为变量名


有没有办法在
sqldf
查询中获得带有下划线的变量名?

您可以在
sql
代码周围使用
paste0
,以便r将
color\u num
计算为2,然后将其粘贴到一个
sql
语句中

library(sqldf)
    A <- data.frame(col1 = c(1,2,3),col2 = c("red","blue","green"))
    color_num <- 2

    fn$sqldf(paste0("select * from A where col1 >=",color_num))
您可以使用反勾号:

fn$sqldf("select * from A where col1 >= `color_num`")
##   col1  col2
## 1    2  blue
## 2    3 green

谢谢@Mike。我尝试过在变量名周围包装
[]
,但没有效果。关于使用
paste0
构造字符串,这并不理想,因为变量名可能出现在复杂sql字符串中的许多地方,因此我必须
paste0
将许多不同的子字符串放在一起。理想的解决方案是允许在
sqldf
中使用标准变量名来容纳下划线,下划线通常出现在变量名中。有办法吗?我明白问题所在。这可能是
sql
包中的一个bug,这里有一个解决方案,您可以将
\ucode>更改为
,这样代码就可以工作了。如果您喜欢,我将使用
lappy
对其进行扩展,以更改所有变量-<代码>分配(gsub(““,”),setdiff(ls(),c(“A”)),获取(setdiff(ls(),c(“A”))
fn$sqldf("select * from A where col1 >= `color_num`")
##   col1  col2
## 1    2  blue
## 2    3 green