这是我的代码。它无法帮助您进行着色,但我从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
r
然后再删除它,你可以将其放在 local({ })
块中。虽然如此,这是一个很好的答案,我喜欢 X11 配置! - Aaron McDaidhelp(Startup)
中展示的local({ ... })
是我最近在Rprofile.site
中经常使用的。已经有一段时间没有用到X11 hack了 :) - Dirk Eddelbuettel我不喜欢每次都要输入完整的单词“head”、“summary”和“names”,所以我使用别名。
你可以将别名放入你的.Rprofile文件中,但是你必须使用函数的完整路径(例如utils :: head),否则它将无法工作。
# aliases
s <- base::summary
h <- utils::head
n <- base::names
编辑:回答你的问题,你可以使用colorout包,在终端中拥有不同的颜色。很酷!:-)
n
会亲自咬我的后部。 - Roman Luštrik.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 Wrightsum <- base::summary
。那个并不是一个好主意。 - Tomcolorout
包的说明:"""该软件包已被归档:它使用了 CRAN 政策不允许的非 API 入口点。""" - isomorphismesoptions(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
在某些情况下,因子非常有用(例如在图形排序中实现),但大多数情况下都是麻烦。
我喜欢保存我的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")))
}
}
这是我的方法。我经常使用主要的CRAN仓库,并编写了代码,使得可以轻松地引入正在开发中的软件包代码。
.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"))
}
这里有两个我发现在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()))))
}
.repath
正在如此地进入我的.Rprofile
。 - Waldir Leonciosnippet wpp
\
r paste(""", gsub("\\", "/", readClipboard()), """, sep = "")`` - jamesguy0121我知道一个更动态的技巧,可以使用完整的终端宽度,它尝试从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)}
)
COLUMNS
未设置时,您可以尝试width = as.integer(system('tput cols',intern=TRUE)
作为备选方案。 - shabbychef这是我在 Mac 和 Linux 上设计的 ~/.Rprofile 内容。
这些内容可以更方便地查看错误信息。
options(showWarnCalls=T, showErrorCalls=T)
我不喜欢CRAN的菜单选择,所以将其设置为一个好的选择。
options(repos=c("http://cran.cnr.Berkeley.edu","http://cran.stat.ucla.edu"))
更多历史!
Sys.setenv(R_HISTSIZE='100000')
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
中,然后根据需要进行源代码调用。
我的大部分个人功能和加载的库都在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")')
.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))
}
?new.env
、?assign
和?sys.source
。如果您无法让其正常工作,请在SO上发布新的问题,我相信您会得到答案。 - Gavin Simpsonmy.as.Date
可能被 Lubridate
软件包所取代。我说的对吗? - isomorphismes
.Rprofile
文件不应包含任何改变结果的代码。您可以包括更改 R 外观的内容(例如options("width"=160)
)或更改默认 CRAN 镜像的内容(例如options(repos = c(CRAN = "http://cran.rstudio.com"))
)。然而,不要加载包、更改常用函数的默认选项、定义函数等。您的代码应该是独立完整的,并且可以在没有特定.Rprofile
文件的情况下重新产生结果。 - user2503795.Rprofile
中容易/可能吗? - Aaron McDaid.Rprofile
是一个适当的地方来进行应用程序更改。其次,你的问题应该是一个独立的 SO 问题。我尝试使用类似于我们在 食品检查 项目中所做的模式(请参见代码布局和每个脚本顶部的初始化步骤)。 - geneorama