我尝试使用tibble
包将R data.frame
对象(或Postgres
)写入RPostgres
数据库。在文档之后,我尝试使用dbWriteTable
函数。
但是,我意识到方法中没有field.types
的规范。在这里,我提供了一个最小的示例,您可以在输入具有POSIXct
时间戳(并将时间戳被解释为字符时传递)时看到方法失败。
library(dplyr)
library(DBI)
library(RPostgres)
library(tibble)
conn <- dbConnect(RPostgres::Postgres(),
host = url$host,
port = url$port,
dbname = url$dbname,
user = url$user,
password = url$password
)
test <- tibble(
words = c("hallo","ja", "nein"),
value = c(3,4,5),
time= as.POSIXct(c("2016-05-04 04:32","2016-06-02 09:37","2016-07-12 10:43")))
test2 <- tibble(
words = c("hallo","ja", "nein"),
value = c(3,4,5),
time= c("2016-05-04 04:32","2016-06-02 09:37","2016-07-12 10:43"))
dbWriteTable(conn = conn, name = "words", value = test)
> Error in eval(substitute(expr), envir, enclos) :
> ERROR: invalid input syntax for type real: "2016-05-04 04:32:00"
> CONTEXT: COPY words, line 1, column time: "2016-05-04 04:32:00"
dbWriteTable(conn = conn, name = "words2", value = test2)
> [1] TRUE
是否有人知道使用Postgres
在R
中使用时间戳编写表格的更好方法?
答案 0 :(得分:0)
在PostgreSQL
包中使用RPostgreSQL
驱动程序有效。此外,第三个时间戳的格式与as.POSIXct的默认值不匹配 - 小时数字太多。所以我将"2016-07-12 010:43"
更改为"2016-07-12 10:43"
,您应该会发现它工作正常。
library(dplyr)
library(DBI)
library(RPostgreSQL)
library(tibble)
#connect to db
url <- list(user="postgres",password="postgres",dbname="test")
conn <- dbConnect(drv="PostgreSQL", user=url$user, password=url$password, dbname = url$dbname)
test <- tibble(
words = c("hallo","ja", "nein"),
value = c(3,4,5),
time= as.POSIXct(c("2016-05-04 04:32","2016-06-02 09:37","2016-07-12 10:43")))
test2 <- tibble(
words = c("hallo","ja", "nein"),
value = c(3,4,5),
time= c("2016-05-04 04:32","2016-06-02 09:37","2016-07-12 010:43"))
dbWriteTable(conn = conn, name = "words", value = test)
[1] TRUE
dbWriteTable(conn = conn, name = "words2", value = test2)
[1] TRUE
dbDisconnect(conn)