【问题标题】:R : doubles quotes in a paste, how to get rid of the backlashesR:粘贴中的双引号,如何摆脱反冲
【发布时间】:2018-03-30 13:08:13
【问题描述】:

这似乎是一个老生常谈的问题,但我发现的所有帖子都不适用于我的情况。我有这个简单的 SQL 查询:

min.t <- "2017-10-17 00:00:00"
max.t <- "2017-10-17 08:00:00"
query <- paste0('select * from pred where \"current.time\">\"',min.t,'\" and 
\"current.time\"<\"',max.t,'\"')
"select * from pred where \"current.time\">\"2017-10-17 00:00:00\" and 
\"current.time\"<\"2017-10-17 08:00:00\""

如您所见,由于引用简单,反作用力仍然存在。我需要保留查询的简单引号,因为列名包含一个点。如果我从粘贴中删除反冲,我会得到相同的结果:

paste0('select * from pred where "current.time">"',min.t,'" and 
"current.time"<"',max.t,'"')
[1] "select * from pred where \"current.time\">\"2017-10-17 00:00:00\" and 
\"current.time\"<\"2017-10-17 08:00:00\""

 gsub('\\\\', '', query)

似乎忽略了他们。

【问题讨论】:

  • 为什么不使用方括号或反引号(SQLite 中的转义符号)而不是双引号(ANSI-SQL 中的通用标识符符号)?

标签: sql r sqlite


【解决方案1】:

我会将您的原始 SQLite 查询表述为:

select *
from pred
where
    "current.time" > '2017-10-17 00:00:00' and
    "current.time" < '2017-10-17 08:00:00';

在 R 中,您可以在字符变量中使用上述查询,例如

query <- paste0("select * from pred where \"current.time\" > '2017-10-17 00:00:00' ",
                "and \"current.time\" < '2017-10-17 08:00:00'")

请注意,我们可以对您的WHERE 子句进行简化并使用BETWEEN,这会导致:

query <- paste0("select * from pred where \"current.time\" between ",
                "'2017-10-17 00:00:01' and '2017-10-17 07:59:59'")

【讨论】:

  • 谢谢,但鉴于我的专栏名称中有一个点,看来我需要为它们加上双引号。尝试使用您的示例给出: query '",min.t,"' ", "and current.time
  • @XavierPrudent 你说得对,需要用点转义列名。首先,您真的不应该在列名中使用点。您可以尝试运行我的原始查询并查看它是否有效吗?然后让我知道相同的查询是否适用于 R。
  • 它有效 :) 我只是不明白为什么。你用双引号替换了简单的引号。它们和 bash 中的效果一样吗?
  • @XavierPrudent 我所做的唯一更改是不在时间戳文字周围加上双引号。正如我在回答中提到的,双引号可以解释为转义的列名。
猜你喜欢
  • 2022-12-07
  • 2012-10-28
  • 2014-02-17
  • 2013-02-13
  • 2015-12-06
  • 2013-03-23
  • 2019-07-02
  • 1970-01-01
  • 2016-03-24
相关资源
最近更新 更多