R

From Smithnet Wiki
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