6

我从 postgresql 中获取了一组日期,它们看起来是正确的:

[1] "2007-07-13" "2007-07-14" "2007-07-22" "2007-07-23" "2007-07-24"
[6] "2007-07-25" "2007-08-13" "2007-08-14" "2007-08-15" "2007-08-16"
etc.

然后我想对它们运行一个循环来制作新的 sql 语句来获取其他一些数据集(是的,我知道我在做什么,不可能在数据库服务器中完成所有处理)

所以我尝试了

for(date in geilodates)
 mapdate(date,geilo)
Error in postgresqlExecStatement(conn, statement, ...) : 
  RS-DBI driver: (could not Retrieve the result : ERROR:  invalid input syntax for type date: "13707"
LINE 1: ...id_date_location where not cowid is null and date='13707' or...

mapdate 是我编写的一个函数,其中日期的使用是

sql=paste('select * from gps_coord where cowid=',cowid," and date='",date,"'",sep='')

所以,发生的事情是,在我尝试将 sql 粘贴在一起之前,R 默默地将我的格式化日期转换为它们的整数表示。

如何获得日期的原始文本表示?我试过了

for(date in geilodates){
  d=as.Date(date,origin="1970-01-01")
  mapdate(d,geilo)
}
Error in charToDate(x) : 
character string is not in a standard unambiguous format

而且我还没有设法找到任何其他函数来创建日期字符串(或将日期“服务”为列出变量时得到的字符串

4

2 回答 2

7

Thanks to wush978 for pointing me in the right direction, In the end I had to do:

for(d in geilodates){
 date=format(as.Date(d,origin="1970-01-01"))
 mapdate(date,geilo)
}

For some reason, inside the loop the "date" variable was seen as an integer, so I explicitely had to convert it to a date and then format it...

于 2013-01-24T09:10:54.847 回答
5

尝试?format.Date

x <- Sys.Date()
class(x)
class(format(x))

在 R 中,类的数据Date是数字类型。表示为字符串的官方方法Date是调用format.

我怀疑date在你的情况下定义了格式,所以paste 有一些意想不到的事情。

也许你需要format(x, "%Y-%m-%d")输入你的paste函数而不是date告诉 R 你想要哪种格式的日期。

于 2013-01-24T08:44:33.637 回答