日期显示为数字

Mor*_*kel 5 postgresql r date

我从 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.
Run Code Online (Sandbox Code Playgroud)

然后我想对它们运行一个循环来创建新的 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...
Run Code Online (Sandbox Code Playgroud)

mapdate 是我写的一个函数,里面日期的使用是

sql=paste('select * from gps_coord where cowid=',cowid," and date='",date,"'",sep='')
Run Code Online (Sandbox Code Playgroud)

所以,发生的事情是,在我尝试将 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
Run Code Online (Sandbox Code Playgroud)

而且我还没有找到任何其他函数来创建日期字符串(或将日期作为我在列出变量时得到的字符串“提供”)

Mor*_*kel 6

感谢 wush978 为我指明了正确的方向,最后我不得不这样做:

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

出于某种原因,在循环内部,“日期”变量被视为一个整数,因此我必须明确地将其转换为日期,然后对其进行格式化...

  • “...出于某种原因”是因为`is.vector(Sys.Date())` 是`FALSE`。`help('for')` 说:“seq:一个表达式求值到一个向量......或一个对列表或'NULL'”,所以发生的事情(本质上)是 `as.vector(Sys.Date()) #15729`。 (2认同)

wus*_*978 5

尝试 ?format.Date

x <- Sys.Date()
class(x)
class(format(x))
Run Code Online (Sandbox Code Playgroud)

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

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

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