Search code examples
rpostgresqlr-dbi

Adding Numbers to Postgres Database using RPostgres


I have enjoyed working with the RPostgres (R package) for a while now and it works very well on most things. One thing I recently ran into is it seems to automatically convert numeric types in R into REAL in my Postgres database. The REAL type seems to be very imprecise so I would ideally like to cast my numerics into a type that can handle many more digits (nothing crazy but at least 10 or so). Anyone know how I can accomplish that? Here is an example before of adding numbers...

library(RPostgres)
library(DBI)
library(tibble)

con <- DBI::dbConnect(RPostgres::Postgres(),
                     host = 'localhost',
                     port = 5432,
                     user = 'test',
                     password = '')

test_tbl <- tibble::tibble(number_use =  434.94823992383445)

DBI::dbWriteTable(con, "test_tbl", test_tbl)

Solution

  • Though part of the DBI specifications that may or may not be integated into specific API, here being RPostgres, consider field.types argument, passing a named list of column names and types.

    Below uses Postgres NUMERIC(precision, scale) type (synonymous to DECIMAL) where precision is total number of digits for value both before and after decimal point with scale being number of needed decimal digits.

    # WITH NUMERIC(precision, scale)
    dbWriteTable(con, "test_tbl", test_tbl, field.types=list(number_use="numeric(##,##)"))