286

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.

Urb
  • 115
  • 6
gappy
  • 10,095
  • 14
  • 54
  • 73
  • 31
    Unfortunately the question is closed, but I strongly think that the right answer is "nothing". Instead of using .Rprofile, I suggest keeping an initialization script at the top level of every project that gets invokes it at the beginning of every script in your project. That keeps your work reproducible across other users via source control. But, there are some brilliant answers here! I'll be putting some of these ideas in my own initialization script(s). – geneorama Jan 11 '14 at 05:32
  • 19
    @geneorama - Good comment but I would qualify your answer a little: The `.Rprofile` should not include any code that changes the results. What you can include is stuff that changes the appearance of R (e.g. `options("width"=160)`) or the default CRAN mirror (e.g. `options(repos = c(CRAN = "http://cran.rstudio.com"))`). Do not, however, load packages, change the default options of regularly used functions, define function etc. Your code should be self-contained and reproduce the results without your particular `.Rprofile` file. – user2503795 May 04 '14 at 12:18
  • @geneorama, where should I put custom functions then? Perhaps in a separate package/namespace? Is that easy/possible within `.Rprofile`? – Aaron McDaid Aug 27 '15 at 10:55
  • 2
    @aaron-mcdaid First @user2503795 is absolutely right, `.Rprofile` is an appropriate place to make application changes. Second, your question should be a separate SO question. I try to use a pattern similar to what we did in our [food inspection](https://github.com/Chicago/food-inspections-evaluation) project (see the code layout, and initialization steps at the top of each script). – geneorama Aug 28 '15 at 19:07

24 Answers24

98

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"="okular")         # on Linux, use okular as the pdf viewer
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
  • I'm not sure, but I think that now X11.options has been replace by windows.options. Is that true? – Manuel Ramón Nov 04 '11 at 07:17
  • Instead of creating `r` and then `rm`-ing it, you could put that inside a `local({ })` block. Good answer though, I love the X11 config! – Aaron McDaid Aug 27 '15 at 10:51
  • Yes, the `local({ ... })` as shown in `help(Startup)` is what I usually do these days in `Rprofile.site`. Haven't needed the X11 hack in a while :) – Dirk Eddelbuettel Aug 27 '15 at 11:02
61

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

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

# aliases
s <- base::summary
h <- utils::head
n <- base::names

EDIT: to answer your question, you can use the colorout package to have different colors in the terminal. Cool! :-)

dalloliogm
  • 8,718
  • 6
  • 45
  • 55
  • I like that. Those are three functions that I use all the time. – Brandon Bertelsen Jan 27 '10 at 16:31
  • 11
    I think `n` would bite me, personally, in the posterior while debugging. – Roman Luštrik Nov 10 '11 at 08:55
  • 3
    Fine for interactive R use, but these aren't portable — don't put them in your (written) code! – Vince Mar 27 '12 at 20:00
  • 25
    If you ever delete all objects in your global environment, then the aliases above will also be deleted. You can prevent that by hiding these in an environment. `.startup <- new.env()` `assign("h", utils::head, env=.startup)` `assign("n", base::names, env=.startup)` `assign("ht", function(d) rbind(head(d,6),tail(d,6)) , env=.startup)` `assign("s", base::summary, env=.startup)` `attach(.startup)` – Kevin Wright Apr 11 '12 at 13:40
  • 12
    I tried this great idea, but I already used s so I did `sum <- base::summary`. That *wasn't* such a great idea. – Tom Oct 02 '12 at 03:49
  • `tr` for `traceback` and `br` for `browser` are also good typing savers. – Richie Cotton Jan 23 '13 at 11:36
  • 1
    re `colorout`: """This package has been archived: it used non-API entry points not allowed by the CRAN policies.""" – isomorphismes Jul 02 '13 at 00:29
  • In order to prevent the aliases from being overridden by variable assignments, you can add the aliases to `~/.myfuns.R` and add this to `~/.Rprofile`: `while("myfuns"%in%search())detach("myfuns");source("~/.myfuns.R",attach(NULL,name="myfuns",warn.conflicts=F))`. The `detach` function avoids creating a duplicate entry if you reload `~/.Rprofile`. The help page of `attach` says that "One useful 'trick' is to use `what = NULL` (or equivalently a length-zero list) to create a new environment on the search path into which objects can be assigned by `assign` or `load` or `sys.source`." – nisetama Aug 27 '22 at 06:40
60
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
  • 8,991
  • 6
  • 42
  • 49
  • Eduardo - Interesting, what are the advantages of not using factors? – medriscoll Sep 08 '09 at 18:05
  • 30
    +1 I wish this was the default in R. – Iterator Oct 22 '11 at 03:36
  • 5
    Note that character vectors only seem to use less memory (two hundred bytes or so) on 32-bit systems. On 64-bit systems factors use considerably less. https://stat.ethz.ch/pipermail/r-help/2012-August/321919.html – Ari B. Friedman Aug 18 '12 at 13:51
  • +1 Thanks for pointing out some of the major issues with factors. SAS's format system has many advantages over this, imo. When reading from text, stringsAsFactors is always set to false. However, for data transfer, I avoid reading from spreadsheet wherever possible. – AdamO Jul 06 '15 at 22:27
  • 5
    In R versions >=4.0.0, this is the new default. Hooray! – Andreï V. Kostyrka May 14 '21 at 20:48
27

Here are two functions I find handy for working with windows.

The first converts the \s to /.

.repath <- function() {
   cat('Paste windows file path and hit RETURN twice')
   x <- scan(what = "")
   xa <- gsub('\\\\', '/', x)
   writeClipboard(paste(xa, collapse=" "))
   cat('Here\'s your de-windowsified path. (It\'s also on the clipboard.)\n', xa, '\n')
 }

The second opens the working directory in a new explorer window.

getw <- function() {
    suppressWarnings(shell(paste("explorer",  gsub('/', '\\\\', getwd()))))
}
Tom
  • 4,860
  • 7
  • 43
  • 55
  • 3
    This `.repath` is _so_ getting into my .Rprofile. – Waldir Leoncio Feb 20 '14 at 20:33
  • 1
    I wrote [a RStudio addin](https://github.com/dracodoc/mischelper) that included this feature. You just copy the path, click a menu from RStudio, and the converted path will be inserted into your cursor location. This should save some keystrokes. – dracodoc Jan 17 '17 at 01:06
  • 1
    I hate the windows path issue SOOO much. I think I might have even a better solution. I added a snippet. so all I have to do is type wpp then press tab and my copied path shows up. Here is the code. `snippet wpp` `\`r paste("\"", gsub("\\\\", "/", readClipboard()), "\"", sep = "")\`` – jamesguy0121 Jun 21 '19 at 00:12
27

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")))
        }
}
medriscoll
  • 26,995
  • 17
  • 40
  • 36
Jeff
  • 1,426
  • 8
  • 19
26

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
  • 102,019
  • 32
  • 183
  • 245
18

I've got this, more dynamic trick to use full terminal width, which 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.

tonytonov
  • 25,060
  • 16
  • 82
  • 98
  • 1
    When ```COLUMNS``` is not set, you can try ```width = as.integer(system('tput cols',intern=TRUE)``` as a backstop. – shabbychef Dec 26 '12 at 23:52
17

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
  • 15,977
  • 2
  • 23
  • 25
  • 1
    Heh, I thought about naming an R GUI "Arrr"- this is a much easier way to add some piratey goodness. – Sharpie Jul 28 '09 at 02:22
  • 2
    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 Jul 28 '09 at 02:38
  • 1
    It explains why @Dirk was setting his hook in his script... – James Jul 14 '11 at 16:33
  • 1
    "Avast Ye" is [non-standard Pirate](http://en.wiktionary.org/wiki/avast#Usage_notes). I prefer my Pirate to conform to standards. Also, it means ~"hold tight", so wouldn't it make more sense at the start? :P – naught101 Jun 21 '12 at 03:31
  • 2
    Actually it makes perfect sense at the end. For upon exiting the r domain we return to the lesser environment around it and must again deal with spreadsheets and ad-hoc text files. – kpierce8 Apr 26 '13 at 18:32
17

Here's from my ~/.Rprofile, designed for Mac and Linux.

These make errors easier to see.

options(showWarnCalls=T, showErrorCalls=T)

I hate the CRAN menu choice, so set to a good one.

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

More history!

Sys.setenv(R_HISTSIZE='100000')

The following is for running on Mac OSX from the terminal (which I greatly prefer to R.app because it's more stable, and you can organize your work by directory; also make sure to get a good ~/.inputrc). By default, you get an X11 display, which doesn't look as nice; this instead gives a quartz display same as the GUI. The if statement is supposed to catch the case when you're running R from the terminal on Mac.

f = pipe("uname")
if (.Platform$GUI == "X11" && readLines(f)=="Darwin") {
  # http://www.rforge.net/CarbonEL/
  library("grDevices")
  library("CarbonEL")
  options(device='quartz')
  Sys.unsetenv("DISPLAY")
}
close(f); rm(f)

And preload a few libraries,

library(plyr)
library(stringr)
library(RColorBrewer)
if (file.exists("~/util.r")) {
  source("~/util.r")
}

where util.r is a random bag of stuff I use, under flux.

Also, since other people were mentioning console width, here's how I do it.

if ( (numcol <-Sys.getenv("COLUMNS")) != "") {
  numcol = as.integer(numcol)
  options(width= numcol - 1)
} else if (system("stty -a &>/dev/null") == 0) {
  # mac specific?  probably bad in the R GUI too.
  numcol = as.integer(sub(".* ([0-9]+) column.*", "\\1", system("stty -a", intern=T)[1]))
  if (numcol > 0)
    options(width=  numcol - 1 )
}
rm(numcol)

This actually isn't in .Rprofile because you have to re-run it every time you resize the terminal window. I have it in util.r then I just source it as necessary.

Brendan OConnor
  • 9,624
  • 3
  • 27
  • 25
  • 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. – Richard Herron Aug 04 '10 at 21:51
  • 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 Aug 05 '10 at 23:08
  • I feel like these window-resizing scripts could usefully be a package. Do you agree? – isomorphismes Nov 10 '11 at 05:51
16

Here are mine:

.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))
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 1
    you should not post the address of your institution's proxy on a public website. – dalloliogm Jan 28 '10 at 15:22
  • 13
    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 Mar 02 '10 at 18:12
  • 2
    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 Oct 04 '10 at 14:05
  • 4
    @Keith assign them to an environment and attach the environment to the search path, then clean up. If the functions are in a separate file, you can source directly into the environment. See `?new.env`, `?assign` and `?sys.source`. If you can't get it to work, post a new Q on SO and I'm sure you'll get Answers. – Gavin Simpson Mar 30 '11 at 12:17
  • Your `my.as.Date` might be superseded by the `Lubridate` package. Am I right? – isomorphismes Nov 10 '11 at 04:20
11

Make data.frames display somewhat like 'head', only without having to type 'head'

print.data.frame <- function(df) {
   if (nrow(df) > 10) {
      base::print.data.frame(head(df, 5))
      cat("----\n")
      base::print.data.frame(tail(df, 5))
   } else {
      base::print.data.frame(df)
   }
}

(From How to make 'head' be applied automatically to output? )

Community
  • 1
  • 1
Hugh Perkins
  • 7,975
  • 7
  • 63
  • 71
11
sink(file = 'R.log', split=T)

options(scipen=5)

.ls.objects <- function (pos = 1, pattern, order.by = "Size", decreasing=TRUE, head =     TRUE, n = 10) {
  # based on postings by Petr Pikal and David Hinds to the r-help list in 2004
  # modified by: Dirk Eddelbuettel (http://stackoverflow.com/questions/1358003/tricks-to-    manage-the-available-memory-in-an-r-session) 
  # I then gave it a few tweaks (show size as megabytes and use defaults that I like)
  # a data frame of the objects and their associated storage needs.
  napply <- function(names, fn) sapply(names, function(x)
          fn(get(x, pos = pos)))
  names <- ls(pos = pos, pattern = pattern)
  obj.class <- napply(names, function(x) as.character(class(x))[1])
  obj.mode <- napply(names, mode)
  obj.type <- ifelse(is.na(obj.class), obj.mode, obj.class)
  obj.size <- napply(names, object.size) / 10^6 # megabytes
  obj.dim <- t(napply(names, function(x)
            as.numeric(dim(x))[1:2]))
  vec <- is.na(obj.dim)[, 1] & (obj.type != "function")
  obj.dim[vec, 1] <- napply(names, length)[vec]
  out <- data.frame(obj.type, obj.size, obj.dim)
  names(out) <- c("Type", "Size", "Rows", "Columns")
  out <- out[order(out[[order.by]], decreasing=decreasing), ]
  if (head)
    out <- head(out, n)
  out
}
Patrick McCann
  • 484
  • 4
  • 11
10

I often have a chain of debug calls I need to call and uncommenting them can be very tedious. With the help of the SO community, I went for the following solution and inserted this into my .Rprofile.site. # BROWSER is there for my Eclipse Tasks so that I have an overview of browser calls in the Task View window.

# turn debugging on or off
# place "browser(expr = isTRUE(getOption("debug"))) # BROWSER" in your function
# and turn debugging on or off by bugon() or bugoff()
bugon <- function() options("debug" = TRUE)
bugoff <- function() options("debug" = FALSE) #pun intended
Community
  • 1
  • 1
Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197
9

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,236
  • 1
  • 9
  • 14
8
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
  • 43,807
  • 34
  • 160
  • 255
8

Stephen Turner's post on .Rprofiles has several useful aliases and starter functions.

I find myself using his ht and hh often.

#ht==headtail, i.e., show the first and last 10 items of an object
ht <- function(d) rbind(head(d,10),tail(d,10))

# Show the first 5 rows and first 5 columns of a data frame or matrix
hh <- function(d) d[1:5,1:5]
Ram Narasimhan
  • 22,341
  • 5
  • 49
  • 55
  • There's a package called [BurStMisc](http://cran.r-project.org/web/packages/BurStMisc/index.html) that contains a function called `corner` which does the same as your `hh` function and a bit more. ;) – Waldir Leoncio Feb 20 '14 at 19:34
7

Here's mine. Nothing too innovative. Thoughts on why particular choices:

  • I went with setting a default for stringsAsFactors because I find it extremely draining to pass it as an argument each time I read a CSV in. That said, it has already caused me some minor vexation when using code written on my usual computer on a computer which did not have my .Rprofile. I'm keeping it, though, as the troubles it has caused pale in comparison to the troubles not having it set everyday used to cause.
  • If you don't load the utils package before options(error=recover), it cannot find recover when placed inside an interactive() block.
  • I used .db for my dropbox setting rather than options(dropbox=...) because I use it all the time inside file.path and it saves much typing. The leading . keeps it from appearing with ls().

Without further ado:

if(interactive()) {
    options(stringsAsFactors=FALSE)
    options(max.print=50)
    options(repos="http://cran.mirrors.hoobly.com")
}

.db <- "~/Dropbox"
# `=` <- function(...) stop("Assignment by = disabled, use <- instead")
options(BingMapsKey="blahblahblah") # Used by taRifx.geo::geocode()

.First <- function() {
    if(interactive()) {
        require(functional)
        require(taRifx)
        require(taRifx.geo)
        require(ggplot2)
        require(foreign)
        require(R.utils)
        require(stringr)
        require(reshape2)
        require(devtools)
        require(codetools)
        require(testthat)
        require(utils)
        options(error=recover)
    }
}
Ari B. Friedman
  • 71,271
  • 35
  • 175
  • 235
7

Here's a little snippet for use exporting tables to LaTeX. It changes all the column names to math mode for the many reports I write. The rest of my .Rprofile is pretty standard and mostly covered above.

# Puts $dollar signs in front and behind all column names col_{sub} -> $col_{sub}$

amscols<-function(x){
    colnames(x) <- paste("$", colnames(x), "$", sep = "")
    x
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
N8TRO
  • 3,348
  • 3
  • 22
  • 40
7

Here's mine, including some of the mentioned ideas.

Two things you might want to look at:

  • .set.width() / w() update your print width to the one of the terminal. Unfortunately I did not find a way to do this automatically on terminal resize - R documentation mentions this is done by some R interpreters.
  • history is saved every time together with a timestamp and the working directory

.

.set.width <- function() {
  cols <- as.integer(Sys.getenv("COLUMNS"))
  if (is.na(cols) || cols > 10000 || cols < 10)
    options(width=100)
  options(width=cols)
}

.First <- function() {
  options(digits.secs=3)              # show sub-second time stamps
  options(max.print=1000)             # do not print more than 1000 lines
  options("report" = c(CRAN="http://cran.at.r-project.org"))
  options(prompt="R> ", digits=4, show.signif.stars=FALSE)
}

# aliases
w <- .set.width

.Last <- function() {
  if (!any(commandArgs()=='--no-readline') && interactive()){
    timestamp(,prefix=paste("##------ [",getwd(),"] ",sep=""))
    try(savehistory("~/.Rhistory"))
   }
}
Florian Bw
  • 746
  • 1
  • 7
  • 16
7

I use the following to get cacheSweave (or pgfSweave) to work with the "Compile PDF" button in RStudio:

library(cacheSweave)
assignInNamespace("RweaveLatex", cacheSweave::cacheSweaveDriver, "utils")
ROLO
  • 4,183
  • 25
  • 41
7

Mine includes options(menu.graphics=FALSE) because I like to Disable/suppress tcltk popup for CRAN mirror selection in R.

Community
  • 1
  • 1
isomorphismes
  • 8,233
  • 9
  • 59
  • 70
5

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 Wright
  • 2,397
  • 22
  • 29
  • 1
    This `setwd` replacement will work better in version: `utils::assignInNamespace("setwd",function(dir) {on.exit(setWindowTitle(base::getwd())); .Internal(setwd(dir))}, "base")` – Marek May 22 '11 at 20:29
5

I found two functions really necessary: First when I have set debug() on several functions and I have resolved the bug, so I want to undebug() all functions - not one by one. The undebug_all() function added as the accepted answer here is the best.

Second, when I have defined many functions and I am looking for a specific variable name, it's hard to find it within all results of the the ls(), including the function names. The lsnofun() function posted here is really good.

Community
  • 1
  • 1
Ali
  • 9,440
  • 12
  • 62
  • 92
5

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.
  • 17,826
  • 11
  • 69
  • 103