Domanda

Ho sempre trovato di avvio file di profilo di altre persone, sia utili ed istruttivi sulla lingua. Inoltre, mentre ho qualche personalizzazione Bash e Vim , non ho nulla per la R.

Ad esempio, una cosa che ho sempre voluto è colori diversi per l'ingresso e l'uscita del testo in una finestra di terminale, e l'evidenziazione della sintassi forse anche.

È stato utile?

Soluzione

Qui è la mia. Essa non vi aiuterà con la colorazione, ma ottenere che da ESS e 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

Altri suggerimenti

Odio digitare le parole piene 'testa', 'sintesi', 'nomi' ogni volta, per cui uso alias.

È possibile inserire gli alias nel file .Rprofile, ma è necessario utilizzare il percorso completo alla funzione (ad esempio utils :: testa) altrimenti non funzionerà.

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

EDIT: per rispondere alla tua domanda, è possibile utilizzare il href="http://cran.r-project.org/web/packages/colorout/" rel="noreferrer"> colorout pacchetto avere colori differenti nel terminale. Freddo! : -)

options(stringsAsFactors=FALSE)

Anche se io in realtà non ho che nella mia .Rprofile, perché potrebbe rompe codice miei coautori, vorrei che fosse il default. Perché?

1) vettori di caratteri utilizzano meno memoria (ma solo appena);

2) Ancora più importante, ci sarebbe evitare problemi quali:

> 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"

e

> 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

I fattori sono grandi quando ne avete bisogno (ad esempio attuazione ordinamento nei grafici), ma un fastidio maggior parte del tempo.

Ecco la mia. Ho sempre usare il repository cran principale, e hanno il codice per rendere più facile fonte di in-sviluppo del codice del pacchetto.

.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"))  
}

Mi piace avermi salvato la cronologia dei comandi R e avendo a disposizione ogni volta che corro R:

Nel guscio o .bashrc:

export R_HISTFILE=~/.Rhistory

in .Rprofile:

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

Qui ci sono due funzioni che trovo utile per lavorare con le finestre.

La prima converte i \s per /.

.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')
 }

Il secondo si apre la directory di lavoro in una nuova finestra di Explorer.

getw <- function() {
    suppressWarnings(shell(paste("explorer",  gsub('/', '\\\\', getwd()))))
}

Ho questo, trick più dinamico da usare larghezza del terminale completo, che cerca di leggere dalla variabile d'ambiente COLUMNS (su 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)}
)

In questo modo R userà l'intera larghezza anche quando si ridimensiona la finestra del terminale.

La maggior parte delle mie funzioni personali e le librerie caricate sono nello script Rfunctions.r

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")')

Ecco dal mio ~ / .Rprofile , progettato per Mac e Linux.

Questi fanno gli errori più facili da vedere.

options(showWarnCalls=T, showErrorCalls=T)

Odio la scelta del menu CRAN, così impostato su un buon compromesso.

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

Più storia!

Sys.setenv(R_HISTSIZE='100000')

Il seguente è per l'esecuzione su Mac OSX dal terminale (che io preferisco di gran lunga a R.app perché è più stabile, e si può organizzare il proprio lavoro per directory, anche fare in modo di ottenere un buon ~ / .inputrc ). Per impostazione predefinita, si ottiene un display X11, che non sembra così bello; questo dà invece un display al quarzo stessa della GUI. La dichiarazione if dovrebbe prendere il caso in cui si sta eseguendo R dal terminale su 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)

E precaricare un paio di librerie,

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

util.r è una borsa casuale di roba io uso , sotto flusso.

Inoltre, dal momento che altre persone sono state menzionare larghezza console, ecco come lo faccio.

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)

Questo in realtà non è in .Rprofile perché bisogna rieseguire ogni volta si ridimensiona la finestra del terminale. Ho in util.r poi ho appena sorgente, se necessario.

Ecco la mia:

.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))
}
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
}

Fai data.frames mostrano un po 'come 'testa', solo senza dover digitare 'testa'

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)
   }
}

( Come rendere 'testa' essere applicato automaticamente per l'uscita? )

Ho spesso una catena di chiamate di debug ho bisogno di chiamare e li decommentando può essere molto noioso. Con l'aiuto della SO comunità , sono andato per la seguente soluzione e inserito questo in la mia .Rprofile.site. # BROWSER è lì per i miei compiti Eclipse in modo da avere una visione d'insieme del browser chiama nella finestra Task View.

# 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

La mia non è troppo di fantasia:

# 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' )
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)

faccio un sacco di lavoro da database MySQL, in modo che collega subito è una manna dal cielo. Vorrei solo che ci fosse un modo di elencare i database avaialble in modo da non dover ricordare tutti i nomi diversi.

post di Stephen Turner su .Rprofiles ha diversi alias utili e le funzioni di avviamento.

mi ritrovo a usare il suo ht e hh spesso.

#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]

Ecco la mia, tra cui alcune delle idee menzionate.

Due cose che si potrebbe desiderare di guardare:

  • .set.width () / w () aggiornare la larghezza di stampa a quella del terminale. Purtroppo non ho trovato un modo per farlo automaticamente ridimensionamento terminale -. Documentazione R menziona questo è fatto da alcuni interpreti R
  • storia viene salvata ogni volta con un timestamp e la directory di lavoro

.

.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"))
   }
}

Io uso il seguente per ottenere cacheSweave (o pgfSweave) per lavorare con il pulsante "Compila PDF" in RStudio:

library(cacheSweave)
assignInNamespace("RweaveLatex", cacheSweave::cacheSweaveDriver, "utils")

La mia include options(menu.graphics=FALSE) perché mi piace Disabilita / sopprimere tcltk comparsa per la selezione specchio CRAN in R .

Ecco la mia. Niente di troppo innovativo. Pensieri su scelte perché particolari:

  • sono andato con la fissazione di un default per stringsAsFactors perché trovo estremamente drenante di passare come argomento ogni volta che leggo un CSV in. Detto questo, mi ha già causato qualche fastidio minore quando si utilizza codice scritto sulla mia solita computer su un computer che non ha avuto il mio .Rprofile. Sto mantenendo, però, come i guai che ha causato pallido in confronto ai problemi non averlo set tutti i giorni utilizzato per provocare.
  • Se non si carica il pacchetto utils prima options(error=recover), non riesce a trovare recuperare una volta disposto all'interno di un blocco di interactive().
  • Ho usato .db per l'impostazione mio set piuttosto che options(dropbox=...) perché io uso per tutto il tempo all'interno file.path e consente di risparmiare molto di battitura. Il . leader impedisce di apparire con ls().

Senza ulteriori indugi:

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)
    }
}

Ecco un piccolo frammento per l'uso tabelle a LaTeX esportazione. Cambia tutti i nomi di colonna per modalità matematica per i numerosi rapporti che scrivo. Il resto della mia .Rprofile è abbastanza standard e in gran parte coperto sopra.

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

amscols<-function(x){
    colnames(x) <- paste("$", colnames(x), "$", sep = "")
    x
}

Ho impostato il mio tema di colore grata nel mio profilo. Ecco altri due modifiche che uso:

# 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)

Ho un R_USER_WORKSPACE variabile d'ambiente che punta alla directory principale dei miei pacchetti. In .Rprofile definisco una funzione Devlib che imposta la directory di lavoro (in modo che i dati () funziona) e fonti di tutti i file .R nella sottodirectory R. È abbastanza simile alla funzione sopra l di Hadley ().

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")

Ho trovato due funzioni davvero necessario: In primo luogo, quando ho posto debug() sulle diverse funzioni e ho risolto il bug, quindi voglio undebug() tutte le funzioni - non uno per volta. La funzione undebug_all() aggiunto come la risposta accettata qui è il migliore.

In secondo luogo, quando ho definito molte funzioni e sto cercando di uno specifico nome di variabile, è difficile da trovare entro tutti i risultati del del ls(), compresi i nomi delle funzioni. La funzione lsnofun() postato qui è veramente buono.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top