R sprintf in sqldf's like

R sprintf in sqldf's like

我想在 R 中使用 sqldf 对 select 所有非 NULL X.1 变量进行循环查询,日期为“11/12/2015”,时间为上午 9 点。示例:

StartDate              X.1
11/12/2015 09:14        A
11/12/2015 09:36        
11/12/2015 09:54        A

日期在从其他查询生成的变量中

nullob<-0
dayminnull<-as.numeric(sqldf("SELECT substr(Min(StartDate),1,03)as hari     from testes")) # this produce "11/12/2015"
  for (i in 1 : 12){
    dday<-mdy(dayminnull)+days(i) #go to next day
    sqlsql <- sprintf("SELECT count([X.1]) FROM testes where StartDate like '% \%s 09: %'", dday)
    x[i]<-sqldf(sqlsql)
    nullob<-nullob+x[i]
}

它带有错误:sprintf 错误("SELECT count([X.1]) FROM testes WHERE StartDate like '%%s 09%'",: 无法识别的格式规范 '%' 请帮忙。提前谢谢你

文档中没有super说清楚,而是一个%后面跟着一个%,也就是%%,就是这样告诉 sprintf 使用文字 %。我们可以很容易地对此进行测试:

sprintf("%% %s %%", "hi")
[1] "% hi %" 

对于您的查询字符串,这应该有效:

sprintf("SELECT count([X.1]) FROM testes where StartDate like '%% %s 09: %%'", dday)

来自?sprintf

The string fmt contains normal characters, which are passed through to the output string, and also conversion specifications which operate on the arguments provided through .... The allowed conversion specifications start with a % and end with one of the letters in the set aAdifeEgGosxX%. These letters denote the following types:

... [Documentation on aAdifeEgGosxX]

  • %: Literal % (none of the extra formatting characters given below are permitted in this case).