我在 R 中有一个具有各种不同数据类型的数据框。在将数据帧从 R 写入 redshift 服务器时,我只收到字符和时间戳值的错误。我在下面添加了 R 代码片段,让您对这个问题有更多的了解。
library(lubridate)
library(dplyr)
dat <- data.frame(id = letters[1:2], x = 2:3, date = now())
dat
str(dat)
drv <- dbDriver("PostgreSQL")
conn <- dbConnect(drv, host="redshift.amazonaws.com", port="5439", dbname="abcd", user="xyz", password="abc")
DBI::dbGetQuery(conn, "DROP TABLE test21;")
DBI::dbGetQuery(conn, "CREATE TABLE test21 ( id VARCHAR(255), x INT, date timestamp);")
chunksize = 100
for (i in 1:ceiling(nrow(dat)/chunksize)) {
query = paste0('INSERT INTO test21 (',paste0(colnames(dat),collapse = ','),') VALUES ')
vals = NULL
for (j in 1:chunksize) {
k = (i-1)*chunksize+j
if (k <= nrow(dat)) {
vals[j] = paste0('(', paste0(dat[k,],collapse = ','), ')')
}
}
query = paste0(query, paste0(vals,collapse=','))
DBI::dbExecute(conn, query)
}
在运行最后一部分时,出现以下错误:
RS-DBI driver: (could not Retrieve the result : ERROR: column "date" is of type timestamp without time zone but expression is of type numeric
HINT: You will need to rewrite or cast the expression.
当我手动将值输入到 Redshift 表中时,结果如预期的那样。
DBI::dbGetQuery(conn, "INSERT INTO test21 (id, x, date) values ('a','2','2019-02-08 15:21:08'),(' b','3','2019-02-08 15:21:08')")
我感觉到这个问题是由一些程序错误引起的。就我在代码中做错的地方请求您的建议。
最佳答案
在数据框的日期字段中,尝试替换
现在()
与
substr(现在(), 1, 19)
关于r - Dataframe 从 R 写入 Redshift 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54590667/