问题描述
我想在 R 中使用 sqldf 进行循环查询,以选择日期为11/12/2015"和上午 9 点的所有非 NULL X.1 变量.示例:
I would like to do a looping query in R using sqldf to that select all non-NULL X.1 variable with date "11/12/2015" and at 9AM. Example :
StartDate X.1
11/12/2015 09:14 A
11/12/2015 09:36
11/12/2015 09:54 A
日期在其他查询生成的变量中
The date is in variable that generated from other query
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]
}
它带有错误:Error in sprintf("SELECT count([X.1]) FROM testes WHERE StartDate like '%%s 09%'", :无法识别的格式规范%"拜托了.提前谢谢你
And it comes with error : Error in sprintf("SELECT count([X.1]) FROM testes WHERE StartDate like '%%s 09%'", : unrecognised format specification '%'Please hellp. thank you in advance
推荐答案
在文档中不是 super 清楚的,而是一个 %
后跟一个 %
,即 %%
,是告诉 sprintf
使用文字 %
的方式.我们可以很容易地对此进行测试:
It's not super clear in the documentation, but a %
followed by a %
, that is %%
, is the way to tell sprintf
to use a literal %
. We can test this fairly easily:
sprintf("%% %s %%", "hi")
[1] "% hi %"
对于您的查询字符串,这应该有效:
For your query string, this should work:
sprintf("SELECT count([X.1]) FROM testes where StartDate like '%% %s 09: %%'", dday)
来自?sprintf
:
字符串 fmt 包含普通字符,这些字符被传递到输出字符串,以及操作的转换规范通过 ...
提供的参数.允许的转换规范以 %
开头,以设置 aAdifeEgGosxX%
.这些字母表示以下类型:
... [关于aAdifeEgGosxX
的文档]
... [Documentation on aAdifeEgGosxX
]
%
:文字%
(在这种情况下,不允许使用下面给出的任何额外格式字符).
%
: Literal%
(none of the extra formatting characters given below are permitted in this case).
这篇关于sqldf 中的 R sprintf 就像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!