【发布时间】:2016-08-31 15:24:09
【问题描述】:
我正在建立一个本地服务器,以便在本地和远程与托管表进行交互。我已经通过Rpostgresql成功连接到本地db,并且可以查询和写表了。
我还没有找到任何关于在 R 中使用数据框行更新表的有前途的帖子。 (对于我的功能,这意味着添加新的观察行,假设我每周更新数字)。
假设 mtcars 表作为 postgres 表上传如下:
postgrestable = mtcars
postgrestable$key = rownames(postgrestable)
postgrestable = postgrestable[, c(12, 1:2)]
head(postgrestable)
我在 R 中有以下数据框:
key = c("MazdaRX4", "Toyota H5", "Chevy Delirium")
mpg = c(21, 22, 31)
cyl = c(6, 4, 6)
df = data.frame(key, mpg, cyl)
head(df)
下面是代码的开头:
库(RPostgreSQL)
# create a connection
# save the password that we can "hide" it as best as we can by collapsing it
pw <- {
"abc123"
}
# loads the PostgreSQL driver
drv <- dbDriver("PostgreSQL")
# creates a connection to the postgres database
# note that "con" will be used later in each connection to the database
con <- dbConnect(drv, dbname = "mydb",
host = "localhost", port = 5432,
user = "postgres", password = pw)
rm(pw) # removes the password
# check for the cartable
dbExistsTable(con, "postgrestable")
#TRUE
#update table (not sure how to structure this)
sql <- "INSERT INTO postgrestable
VALUES ("df")"
我知道在这种情况下行名是不同的,但为了简单起见,我们假设它们是相同的。我将如何将三行'df'插入'postgrestable'?请注意,我做了一个重复项,因为我想考虑到可能存在重复条目的事实。 感谢帮助的家伙
【问题讨论】:
标签: r postgresql