views:

2290

answers:

14

This question is maybe a little too cute, but I have always found startup profile files of other people both useful and instructive about the language. Moreover, while I have some customization for bash and vim, I have nothing for R. For example, one thing I always wanted is different colors for input and output text in a window terminal, and maybe even syntax highlighting.

+6  A: 

Here is mine. It won't help you with the coloring but I get that from ESS and Emacs...

options("width"=160)                # wide display with multiple monitors
options("digits.secs"=3)            # show sub-second time stamps

r <- getOption("repos")             # hard code the US repo for CRAN
r["CRAN"] <- "http://cran.us.r-project.org"
options(repos = r)
rm(r)

## put something this is your .Rprofile to customize the defaults
setHook(packageEvent("grDevices", "onLoad"),
        function(...) grDevices::X11.options(width=8, height=8, 
                                             xpos=0, pointsize=10, 
                                             #type="nbcairo"))  # Cairo device
                                             #type="cairo"))    # other Cairo dev
                                             type="xlib"))      # old default

## from the AER book by Zeileis and Kleiber
options(prompt="R> ", digits=4, show.signif.stars=FALSE)


options("pdfviewer"="kpdf")         # on Linux, use kpdf as the pdf viewer
Dirk Eddelbuettel
+4  A: 

Most of my personal functions and loaded libraries are in the Rfunctions.r script

source("c:\\data\\rprojects\\functions\\Rfunctions.r")


.First <- function(){
   cat("\n Rrrr! The statistics program for Pirates !\n\n")

  }

  .Last <- function(){
   cat("\n Rrrr! Avast Ye, YO HO!\n\n")

  }


#===============================================================
# Tinn-R: necessary packages
#===============================================================
library(utils)
necessary = c('svIDE', 'svIO', 'svSocket', 'R2HTML')
if(!all(necessary %in% installed.packages()[, 'Package']))
  install.packages(c('SciViews', 'R2HTML'), dep = T)

options(IDE = 'C:/Tinn-R/bin/Tinn-R.exe')
options(use.DDE = T)

library(svIDE)
library(svIO)
library(svSocket)
library(R2HTML)
guiDDEInstall()
shell(paste("mkdir C:\\data\\rplots\\plottemp", gsub('-','',Sys.Date()), sep=""))
pldir <- paste("C:\\data\\rplots\\plottemp", gsub('-','',Sys.Date()), sep="")

plot.str <-c('savePlot(paste(pldir,script,"\\BeachSurveyFreq.pdf",sep=""),type="pdf")')
kpierce8
Heh, I thought about naming an R GUI "Arrr"- this is a much easier way to add some piratey goodness.
Sharpie
Ah, thank you. It's good to know I'm not the only one who thinks pirate when firing up R. :-) I swear I'll get over it one of these days.
ars
+5  A: 

Here's mine. I always use the main cran repository, and have code to make it easy to source in-development package code.

.First <- function() {
    library(graphics)
    options("repos" = c(CRAN = "http://cran.r-project.org/"))
    options("device" = "quartz")
}

packages <- list(
  "describedisplay" = "~/ggobi/describedisplay",
  "linval" = "~/ggobi/linval", 

  "ggplot2" =  "~/documents/ggplot/ggplot",
  "qtpaint" =  "~/documents/cranvas/qtpaint", 
  "tourr" =    "~/documents/tour/tourr", 
  "tourrgui" = "~/documents/tour/tourr-gui", 
  "prodplot" = "~/documents/categorical-grammar"
)

l <- function(pkg) {
  pkg <- tolower(deparse(substitute(pkg)))
  if (is.null(packages[[pkg]])) {
    path <- file.path("~/documents", pkg, pkg)
  } else {
    path <- packages[pkg]
  }

  source(file.path(path, "load.r"))  
}

test <- function(path) {
  path <- deparse(substitute(path))
  source(file.path("~/documents", path, path, "test.r"))  
}
hadley
+2  A: 

Mine is not too fancy:

# So the mac gui can find latex
Sys.setenv("PATH" = paste(Sys.getenv("PATH"),"/usr/texbin",sep=":"))

#Use last(x) instead of x[length(x)], works on matrices too
last <- function(x) { tail(x, n = 1) }

#For tikzDevice caching 
options( tikzMetricsDictionary='/Users/cameron/.tikzMetricsDictionary' )
cameron.bracken
+1  A: 

I set my lattice color theme in my profile. Here are two other tweaks I use:

# Display working directory in the titlebar
# Note: This causes demo(graphics) to fail
utils::setWindowTitle(base::getwd())
utils::assignInNamespace("setwd",function(dir)   {.Internal(setwd(dir));setWindowTitle(base::getwd())},"base")

# Don't print more than 1000 lines
options(max.print=2000)
kevin
+2  A: 

Here's mine.

The goquartz() stuff is for running on Mac OSX from the terminal -- it gives a quartz display (like you get when using the GUI) instead of X11.

options(showWarnCalls=T, showErrorCalls=T)
options(repos=c("http://cran.cnr.Berkeley.edu","http://cran.stat.ucla.edu"))

goquartz = function() {
  library("CarbonEL")
  options(device='quartz')
  Sys.unsetenv("DISPLAY")
}

if (.Platform$GUI == "X11") {
  goquartz()
}
Brendan OConnor
If I open R in an xterm window (by typing "R") should it open an R gui-like window? I can't tell any difference by adding this .Rprofile to my home directory.
richardh
No. What this does is, it keeps everything in the console. However, when you plot things, it uses a smarter display device than the default X11 display device.
Brendan OConnor
+2  A: 

I like saving my R command history and having it available each time I run R:

In the shell or .bashrc:

export R_HISTFILE=~/.Rhistory

in .Rprofile:

.Last <- function() {
        if (!any(commandArgs()=='--no-readline') && interactive()){
                require(utils)
                try(savehistory(Sys.getenv("R_HISTFILE")))
        }
}
Jeff
+2  A: 
options(stringsAsFactors=FALSE)

Although I don't actually have that in my .Rprofile, because it might breaks my coauthors' code, I wish it was the default. Why?

1) Character vectors use less memory (but only barely);

2) More importantly, we would avoid problems such as:

> x <- factor(c("a","b","c"))
> x
[1] a b c
Levels: a b c
> x <- c(x, "d")
> x
[1] "1" "2" "3" "d"

and

> x <- factor(c("a","b","c"))
> x[1:2] <- c("c", "d")
Warning message:
In `[<-.factor`(`*tmp*`, 1:2, value = c("c", "d")) :
  invalid factor level, NAs generated

Factors are great when you need them (e.g. implementing ordering in graphs) but a nuisance most of the time.

Eduardo Leoni
Eduardo - Interesting, what are the advantages of not using factors?
dataspora
+3  A: 

Thanks for the interesting post! Here is mine. (I stole some of the above snippets and incorporated them into my .Rprofile). Thank you everyone for contributing.

.First <- function () {
  options(device="quartz")
}

.Last <- function () {
  if (!any(commandArgs() == '--no-readline') && interactive()) {
    require(utils)
    try(savehistory(Sys.getenv("R_HISTFILE")))
  }
}

# Slightly more flexible than as.Date
# my.as.Date("2009-01-01") == my.as.Date(2009, 1, 1) == as.Date("2009-01-01")
my.as.Date <- function (a, b=NULL, c=NULL, ...) {
  if (class(a) != "character")
    return (as.Date(sprintf("%d-%02d-%02d", a, b, c)))
  else
    return (as.Date(a))
}

# Some useful aliases
cd <- setwd
pwd <- getwd
lss <- dir
asd <- my.as.Date # examples: asd("2009-01-01") == asd(2009, 1, 1) == as.Date("2009-01-01")
last <- function (x, n=1, ...) tail(x, n=n, ...)

# Set proxy for all web requests
Sys.setenv(http_proxy="http://192.168.0.200:80/")

# Search RPATH for file <fn>.  If found, return full path to it
search.path <- function(fn, 
     paths = strsplit(chartr("\\", "/", Sys.getenv("RPATH")), split = 
                switch(.Platform$OS.type, windows = ";", ":"))[[1]]) { 
  for(d in paths) 
     if (file.exists(f <- file.path(d, fn))) 
        return(f) 
  return(NULL) 
} 

# If loading in an environment that doesn't respect my RPATH environment
# variable, set it here
if (Sys.getenv("RPATH") == "") {
  Sys.setenv(RPATH=file.path(path.expand("~"), "Library", "R", "source"))
}

# Load commonly used functions
if (interactive())
  source(search.path("afazio.r"))

# If no R_HISTFILE environment variable, set default
if (Sys.getenv("R_HISTFILE") == "") {
  Sys.setenv(R_HISTFILE=file.path("~", ".Rhistory"))
}

# Override q() to not save by default.
# Same as saying q("no")
q <- function (save="no", ...) {
  quit(save=save, ...)
}

# ---------- My Environments ----------
#
# Rather than starting R from within different directories, I prefer to
# switch my "environment" easily with these functions.  An "environment" is
# simply a directory that contains analysis of a particular topic.
# Example usage:
# > load.env("markets")  # Load US equity markets analysis environment
# > # ... edit some .r files in my environment
# > reload()             # Re-source .r/.R files in my environment
#
# On next startup of R, I will automatically be placed into the last
# environment I entered

# My current environment
.curr.env = NULL

# File contains name of the last environment I entered
.last.env.file = file.path(path.expand("~"), ".Rlastenv")

# Parent directory where all of my "environment"s are contained
.parent.env.dir = file.path(path.expand("~"), "Analysis")

# Create parent directory if it doesn't already exist
if (!file.exists(.parent.env.dir))
  dir.create(.parent.env.dir)

load.env <- function (string, save=TRUE) {
  # Load all .r/.R files in <.parent.env.dir>/<string>/
  cd(file.path(.parent.env.dir, string))
  for (file in lss()) {
    if (substr(file, nchar(file)-1, nchar(file)+1) %in% c(".r", ".R"))
      source(file)
  }
  .curr.env <<- string
  # Save current environment name to file
  if (save == TRUE) writeLines(.curr.env, .last.env.file)
  # Let user know environment switch was successful
  print (paste(" -- in ", string, " environment -- ")) 
}

# "reload" current environment.
reload <- resource <- function () {
  if (!is.null(.curr.env))
    load.env(.curr.env, save=FALSE)
  else
    print (" -- not in environment -- ")
}

# On startup, go straight to the environment I was last working in
if (interactive() && file.exists(.last.env.file)) {
  load.env(readLines(.last.env.file))
}
Alfred J Fazio
you should not post the address of your institution's proxy on a public website.
dalloliogm
dalloliogm, this is a private (non public) ip address. There are hundreds of thousands of computers around the world with this exact same ip address. Good luck trying to find out which one is mine!
Alfred J Fazio
alfred, have you found a way to define functions in .Rprofile (as you have here) without having them show up when you do an ls(), aside from naming with an initial '.'? I have too much clutter from the functions that I defined when I ls(). Thanks
Keith
+7  A: 

I hate to type the full words 'head', 'summary', 'names' every time, so I use some aliases.

You can put aliases like this into your .Rprofile file, but you have to put the full path to the function (e.g. utils::head) or otherwise it won't work.

# aliases
s <- base::summary;
h <- utils::head;
n <- base::names;
dalloliogm
I like that. Those are three functions that I use all the time.
Brandon Bertelsen
you could have voted that if you liked it, moreover this question is also community wiki and I won't obtain score from it :-). Anyway, thanks for the comment.
dalloliogm
+1  A: 

I've got this, more dynamic trick to use full terminal width, whick tries to read from the COLUMNS environment variable (on Linux):

tryCatch(
  {options(
      width = as.integer(Sys.getenv("COLUMNS")))},
  error = function(err) {
    write("Can't get your terminal width. Put ``export COLUMNS'' in your \
           .bashrc. Or something. Setting width to 120 chars",
           stderr());
    options(width=120)}
)

This way R will use the full width even as you resize your terminal window.

Branimir Dolicki
+1  A: 

I have an environment variable R_USER_WORKSPACE which points to the top directory of my packages. In .Rprofile I define a function devlib which sets the working directory (so that data() works) and sources all .R files in the R subdirectory. It is quite similar to Hadley's l() function above.

devlib <- function(pkg) {
  setwd(file.path(Sys.getenv("R_USER_WORKSPACE", "."), deparse(substitute(pkg)), "dev"))
  sapply(list.files("R", pattern=".r$", ignore.case=TRUE, full.names=TRUE), source)
  invisible(NULL)
}

.First <- function() {
  setwd(Sys.getenv("R_USER_WORKSPACE", "."))
  options("repos" = c(CRAN = "http://mirrors.softliste.de/cran/", CRANextra="http://www.stats.ox.ac.uk/pub/RWin"))
}

.Last <- function() update.packages(ask="graphics")
Karsten W.
A: 

best thread EVER!

Nm
+1  A: 
setwd("C://path//to//my//prefered//working//directory")
library("ggplot2")
library("RMySQL")
library("foreign")
answer <- readline("What database would you like to connect to? ")
con <- dbConnect(MySQL(),user="root",password="mypass", dbname=answer)

I do a lot of work from mysql databases, so connecting right away is a godsend. I only wish there was a way of listing the avaialble databases so I wouldn't have to remember all the different names.

Brandon Bertelsen
silly me dbGetQuery(con, "show databases;")
Brandon Bertelsen