专家R用户,你的.Rprofile中有什么?

gap*_*ppy 266 terminal customization r rprofile

我总是发现其他人的启动配置文件对该语言既有用又有启发性.此外,虽然我有一些BashVim的定制,但我没有R.

例如,我一直想要的一件事是窗口终端中输入和输出文本的不同颜色,甚至可能是语法高亮.

Dir*_*tel 93

这是我的.它不会帮助你着色,但我从ESS和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
Run Code Online (Sandbox Code Playgroud)


dal*_*ogm 58

我讨厌每次输入完整的单词'head','summary','names',所以我使用了别名.

您可以将别名放入.Rprofile文件中,但是您必须使用该函数的完整路径(例如utils :: head),否则它将无效.

# aliases
s <- base::summary
h <- utils::head
n <- base::names
Run Code Online (Sandbox Code Playgroud)

编辑:要回答您的问题,您可以使用colorout包在终端中使用不同的颜色.凉!:-)

  • 如果您删除了全局环境中的所有对象,则上面的别名也将被删除.您可以通过将它们隐藏在环境中来防止这种情况.`.startup < - new.env()``assign("h",utils :: head,env = .startup)``assign("n",base :: names,env = .startup)``assign( "ht",函数(d)rbind(head(d,6),tail(d,6)),env = .startup)``assign("s",base :: summary,env = .startup)``附(.STARTUP)` (25认同)
  • 我尝试了这个好主意,但我已经使用了s所以我做了`sum < - base :: summary`.那*不是一个好主意. (11认同)
  • 我认为`n`会在调试时亲自咬我. (8认同)
  • 交互式R使用很好,但这些不可移植 - 请勿将它们放入您的(书面)代码中! (2认同)

Edu*_*oni 57

options(stringsAsFactors=FALSE)
Run Code Online (Sandbox Code Playgroud)

虽然我的.Rprofile实际上并没有这个,因为它可能会破坏我的共同作者的代码,我希望它是默认的.为什么?

1)字符向量使用较少的内存(但只是勉强);

2)更重要的是,我们会避免以下问题:

> 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"
Run Code Online (Sandbox Code Playgroud)

> 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
Run Code Online (Sandbox Code Playgroud)

当您需要它们时(例如,在图表中实现排序),因素很大,但在大多数情况下都是令人讨厌的.

  • +1我希望这是R中的默认值. (25认同)
  • 请注意,字符向量似乎只在32位系统上使用较少的内存(大约200个字节).在64位系统上,因素使用率要低得多.https://stat.ethz.ch/pipermail/r-help/2012-August/321919.html (5认同)
  • 在 R 版本 &gt;=4.0.0 中,这是新的默认值。万岁! (5认同)

had*_*ley 26

这是我的.我总是使用主要的存储库,并且有代码可以轻松地获取开发中的包代码.

.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"))  
}
Run Code Online (Sandbox Code Playgroud)


Jef*_*eff 26

我喜欢保存我的R命令历史记录,并且每次运行R时都可以使用它:

在shell或.bashrc中:

export R_HISTFILE=~/.Rhistory
Run Code Online (Sandbox Code Playgroud)

in .Rprofile:

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


Tom*_*Tom 22

这里有两个我觉得使用windows的方便的功能.

第一个将\s 转换为/.

.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')
 }
Run Code Online (Sandbox Code Playgroud)

第二个在新的资源管理器窗口中打开工作目录.

getw <- function() {
    suppressWarnings(shell(paste("explorer",  gsub('/', '\\\\', getwd()))))
}
Run Code Online (Sandbox Code Playgroud)

  • 这个`.repath`是_so_进入我的.Rprofile. (2认同)

小智 18

我有这个更动态的技巧来使用完整的终端宽度,它试图从COLUMNS环境变量中读取(在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)}
)
Run Code Online (Sandbox Code Playgroud)

这样,即使调整终端窗口大小,R也将使用全宽.


kpi*_*ce8 17

我的大多数个人函数和加载的库都在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")')
Run Code Online (Sandbox Code Playgroud)

  • 啊,谢谢.很高兴知道我不是唯一一个在开火时认为海盗的人.:-)我发誓我会在这些日子里克服它. (2认同)
  • 实际上它最终是完全合理的.在退出r域时,我们返回到它周围较小的环境,并且必须再次处理电子表格和特殊文本文件. (2认同)

Bre*_*nor 17

这是来自我的〜/ .Rprofile,专为Mac和Linux而设计.

这些使错误更容易看到.

options(showWarnCalls=T, showErrorCalls=T)
Run Code Online (Sandbox Code Playgroud)

我讨厌CRAN菜单的选择,所以设置得很好.

options(repos=c("http://cran.cnr.Berkeley.edu","http://cran.stat.ucla.edu"))
Run Code Online (Sandbox Code Playgroud)

更多历史!

Sys.setenv(R_HISTSIZE='100000')
Run Code Online (Sandbox Code Playgroud)

以下是从终端在Mac OSX上运行的(我非常喜欢R.app,因为它更稳定,你可以按目录组织你的工作;同时确保得到一个好的〜/ .inputrc).默认情况下,你得到一个X11显示器,看起来不太好; 相反,它提供了与GUI相同的石英显示器.if当您从Mac上的终端运行R时,该语句应该会出现这种情况.

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)
Run Code Online (Sandbox Code Playgroud)

并预加载一些库,

library(plyr)
library(stringr)
library(RColorBrewer)
if (file.exists("~/util.r")) {
  source("~/util.r")
}
Run Code Online (Sandbox Code Playgroud)

其中util.r是东西随机袋我用,下通量.

此外,由于其他人提到控制台宽度,这就是我如何做到这一点.

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)
Run Code Online (Sandbox Code Playgroud)

这实际上不存在,.Rprofile因为每次调整终端窗口大小时都必须重新运行它.我有它,util.r然后我只是必要的来源.


小智 16

这是我的:

.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))
}
Run Code Online (Sandbox Code Playgroud)

  • dalloliogm,这是一个私人(非公共)IP地址.全世界有成千上万台计算机使用这个完全相同的IP地址.祝你好运,找出哪一个是我的! (11认同)
  • @Keith将它们分配给环境并将环境附加到搜索路径,然后进行清理.如果函数位于单独的文件中,则可以直接获取环境.参见`?new.env`,`?assign`和`?sys.source`.如果你不能让它工作,在SO上发布一个新的Q,我相信你会得到答案. (4认同)
  • alfred,你有没有找到一种方法来定义.Rprofile中的函数(就像你在这里一样),而不是在你执行ls()时显示它们,除了用初始'.'命名?我对ls()中定义的函数有太多的混乱.谢谢 (2认同)

Pat*_*ann 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
}
Run Code Online (Sandbox Code Playgroud)


Hug*_*ins 11

使data.frames显示有点像'head',只需要输入'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)
   }
}
Run Code Online (Sandbox Code Playgroud)

(如何使'head'自动应用于输出?)


Rom*_*rik 10

我经常需要调用一系列调试调用,取消注释它们可能非常繁琐.在SO社区的帮助下,我选择了以下解决方案并将其插入到我的社区中.Rprofile.site.# BROWSER是否存在我的Eclipse任务,以便在"任务视图"窗口中概述浏览器调用.

# 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
Run Code Online (Sandbox Code Playgroud)


cam*_*ken 9

我不太喜欢:

# 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' )
Run Code Online (Sandbox Code Playgroud)


Bra*_*sen 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)
Run Code Online (Sandbox Code Playgroud)

我从mysql数据库做了很多工作,所以立即连接是天赐之物.我只希望有一种列出avaialble数据库的方法,所以我不必记住所有不同的名称.

  • 愚蠢的我dbGetQuery(con,"show databases;") (4认同)

Ram*_*han 8

Stephen Turner关于.Rprofiles 的帖子有几个有用的别名和启动函数.

我发现自己经常使用他的ht和hh.

#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]
Run Code Online (Sandbox Code Playgroud)


Flo*_* Bw 7

这是我的,包括一些提到的想法.

您可能想要了解的两件事:

  • .set.width()/ w()将您的打印宽度更新为终端之一.不幸的是我没有找到一种方法在终端调整大小时自动执行此操作 - R文档提到这是由一些R解释器完成的.
  • 历史记录每次都与时间戳和工作目录一起保存

.

.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"))
   }
}
Run Code Online (Sandbox Code Playgroud)


ROL*_*OLO 7

我使用以下命令获取cacheSweave(或pgfSweave)以使用RStudio中的"Compile PDF"按钮:

library(cacheSweave)
assignInNamespace("RweaveLatex", cacheSweave::cacheSweaveDriver, "utils")
Run Code Online (Sandbox Code Playgroud)


iso*_*mes 7

Mine包括options(menu.graphics=FALSE)因为我喜欢在R中禁用/禁止用于CRAN镜像选择的tcltk弹出窗口.


Ari*_*man 7

这是我的.没有什么太创新了.关于特定选择原因的思考:

  • 我设置了一个默认值,stringsAsFactors因为我发现每次读取CSV时都会将它作为参数传递给它.这就是说,当我在计算机上使用通常的计算机上编写的代码时,它已经引起了一些小麻烦.没有我的.Rprofile.不过,我保持这种状态,因为与日常生活所造成的麻烦相比,它带来的麻烦变得苍白无力.
  • 如果utils之前未加载包options(error=recover),则在放入interactive()块内时无法找到恢复.
  • 我用于.db我的保管箱设置,而不是options(dropbox=...)因为我一直在里面使用它file.path,它节省了很多打字.领先者不.让它出现ls().

无需再费周折:

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)
    }
}
Run Code Online (Sandbox Code Playgroud)


N8T*_*TRO 7

这里有一小段用于将表导出到LaTeX的片段.它会将我写的许多报告的所有列名更改为数学模式.我的.Rprofile的其余部分非常标准,大部分都在上面介绍.

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

amscols<-function(x){
    colnames(x) <- paste("$", colnames(x), "$", sep = "")
    x
}
Run Code Online (Sandbox Code Playgroud)


Kev*_*ght 5

我在我的个人资料中设置了格子颜色主题.以下是我使用的另外两个调整:

# 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)
Run Code Online (Sandbox Code Playgroud)


Kar*_* W. 5

我有一个环境变量R_USER_WORKSPACE,它指向我的包的顶级目录.在.Rprofile中,我定义了一个函数devlib,它设置工作目录(以便data()工作)并从R子目录中获取所有.R文件.它与上面的Hadley的l()函数非常相似.

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")
Run Code Online (Sandbox Code Playgroud)


Ali*_*Ali 5

我发现了两个非常必要的函数:首先,当我设置debug()了几个函数并且我已经解决了bug时,所以我想要undebug()所有的函数 - 而不是一个一个.该undebug_all()功能添加为接受的答案在这里是最好的.

其次,当我定义了许多函数并且我正在寻找特定的变量名时,很难在ls()包括函数名在内的所有结果中找到它.这里lsnofun()发布的功能非常好.