我总是发现其他人的启动资料文件对该语言既有用又有启发性。此外,虽然我对Bash和Vim进行了一些自定义,但我对R没有任何内容。
例如,我一直想要的一件事是窗口终端中输入和输出文本的颜色不同,甚至可能是语法高亮。
答案 0 :(得分:92)
这是我的。它不会帮助你着色,但我从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
答案 1 :(得分:58)
我讨厌每次输入完整的单词'head','summary','names',所以我使用了别名。
您可以将别名放入.Rprofile文件中,但必须使用该函数的完整路径(例如utils :: head),否则它将无效。
# aliases
s <- base::summary
h <- utils::head
n <- base::names
编辑:要回答您的问题,您可以使用colorout包在终端中使用不同的颜色。凉! : - )
答案 2 :(得分:56)
options(stringsAsFactors=FALSE)
虽然我在.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"
和
> 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
当您需要它们时(例如,在图表中实施排序),因素非常好,但大部分时间都是令人讨厌的。
答案 3 :(得分: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"))
}
答案 4 :(得分:25)
我喜欢保存我的R命令历史记录,并且每次运行R时都可以使用它:
在shell或.bashrc中:
export R_HISTFILE=~/.Rhistory
<。> .Rprofile:
.Last <- function() {
if (!any(commandArgs()=='--no-readline') && interactive()){
require(utils)
try(savehistory(Sys.getenv("R_HISTFILE")))
}
}
答案 5 :(得分:22)
以下是我发现使用Windows的两个功能。
第一个将\
转换为/
。
.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')
}
第二个在新的资源管理器窗口中打开工作目录。
getw <- function() {
suppressWarnings(shell(paste("explorer", gsub('/', '\\\\', getwd()))))
}
答案 6 :(得分: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)}
)
这样,即使调整终端窗口大小,R也会使用全宽。
答案 7 :(得分: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")')
答案 8 :(得分:17)
这是我的~/.Rprofile,专为Mac和Linux而设计。
这些使错误更容易看到。
options(showWarnCalls=T, showErrorCalls=T)
我讨厌CRAN菜单选项,所以设置得很好。
options(repos=c("http://cran.cnr.Berkeley.edu","http://cran.stat.ucla.edu"))
更多历史!
Sys.setenv(R_HISTSIZE='100000')
以下是从终端在Mac OSX上运行的(我非常喜欢R.app,因为它更稳定,你可以按目录整理你的工作;同时确保得到一个好的~/.inputrc) 。默认情况下,你得到一个X11显示器,看起来不太好;相反,它提供了与GUI相同的石英显示器。当您从Mac上的终端运行R时,if
语句应该会出现这种情况。
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)
并预加载一些库,
library(plyr)
library(stringr)
library(RColorBrewer)
if (file.exists("~/util.r")) {
source("~/util.r")
}
其中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)
这实际上不在.Rprofile
中,因为每次调整终端窗口大小时都必须重新运行它。我在util.r
中有它,然后我根据需要提供它。
答案 9 :(得分: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))
}
答案 10 :(得分: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)
}
}
答案 11 :(得分: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
}
答案 12 :(得分:10)
我经常需要调用一系列调试调用,取消注释它们可能非常繁琐。在SO community的帮助下,我选择了以下解决方案并将其插入到我的.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
答案 13 :(得分: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' )
答案 14 :(得分:8)
答案 15 :(得分:8)
Stephen Turner's post有几个有用的别名和启动函数。
我发现自己经常使用他的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]
答案 16 :(得分:7)
我使用以下命令来获取cacheSweave(或pgfSweave)以使用RStudio中的“Compile PDF”按钮:
library(cacheSweave)
assignInNamespace("RweaveLatex", cacheSweave::cacheSweaveDriver, "utils")
答案 17 :(得分:7)
Mine包括options(menu.graphics=FALSE)
,因为我喜欢Disable/suppress tcltk popup for CRAN mirror selection in R。
答案 18 :(得分:7)
这是我的,包括一些提到的想法。
您可能想要了解的两件事:
.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"))
}
}
答案 19 :(得分: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)
}
}
答案 20 :(得分: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
}
答案 21 :(得分: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")
答案 22 :(得分: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)
答案 23 :(得分:5)
我发现了两个非常必要的功能:首先,当我在几个函数上设置debug()
并且我已经解决了这个错误时,所以我希望undebug()
所有函数 - 而不是一个一个。添加undebug_all()
功能作为接受的答案here是最好的。
其次,当我定义了许多函数并且我正在寻找特定的变量名时,很难在ls()
的所有结果中找到它,包括函数名。发布lsnofun()
的{{1}}功能非常好。