R

From Smithnet Wiki
Revision as of 04:53, 8 May 2024 by NickPGSmith (talk | contribs) (2 revisions imported)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Notes

Guides:

source('somefile.R')
sink('somrfile.txt', append=TRUE); # Write (append) to file
sink() # Return to terminal
png('somefile.png') # Redirect to image
plot(x)
dev.off() # Stop writing to image
q() # Quit

Running R from an external script

  • -f something.R

RPostgreSQL

Include lib:

library(RPostgreSQL)

Example of connecting to postgres:

drv <- dbDriver('PostgreSQL')
con <- dbConnect(drv, dbname='somedatabase', user='someuser', pass='somepass')
data <- dbReadTable(con, 'sometable')
head(data, 100)
dbDisconnect(con)
dbUnloadDriver(drv)

Or like this with SQL/fetch (large tables can be streamed):

drv <- dbDriver('PostgreSQL')
con <- dbConnect(drv)
res <- dbSendQuery(con, 'SELECT * from sometable')
data <- fetch(res, n = -1)

See also here