R sprintf在sqldf中就像

Elb*_*ert 1 printf r sqldf

我想在R中使用sqldf进行循环查询,以选择日期为“ 11/12/2015”且在9AM的所有非NULL X.1变量。范例:

StartDate              X.1
11/12/2015 09:14        A
11/12/2015 09:36        
11/12/2015 09:54        A
Run Code Online (Sandbox Code Playgroud)

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

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]
}
Run Code Online (Sandbox Code Playgroud)

它带有错误:sprintf(“ SELECT count([X.1])from Testes WHERE StartDate like'%% s 09%'”中的错误,:无法识别的格式规范'%'请打扰。

Gre*_*gor 5

它不是超级的文件中明确,而是%接着一个%,那就是%%,就是告诉方式sprintf使用文本%。我们可以很容易地测试一下:

sprintf("%% %s %%", "hi")
[1] "% hi %" 
Run Code Online (Sandbox Code Playgroud)

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

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

来自?sprintf

字符串fmt包含传递到输出字符串的普通字符,以及对通过提供的参数进行操作的转换规范...。允许的转换规范以a %开头,以集合中的字母之一结尾aAdifeEgGosxX%。这些字母表示以下类型:

... [有关文档aAdifeEgGosxX]

  • %:立即数%(在这种情况下,不允许使用以下任何多余的格式化字符)。