専門Rユーザーからおります。Rprofile?[定休日]
-
19-09-2019 - |
解決
ここでは私のものです。
...それはカラーリングであなたを助けにはなりませんが、私はその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
他のヒント
私は完全な言葉「頭」、「要約」、「名前」毎回入力するのが嫌いなので、私は別名を使用します。
あなたはあなたの.Rprofileファイルにエイリアスを置くことができますが、それ以外の場合は動作しません機能(例えばutilsの::ヘッド)への完全なパスを使用する必要があります。
# aliases
s <- base::summary
h <- utils::head
n <- base::names
EDIT:あなたの質問に答えるために、あなたは colorout のパッケージ端末内に異なる色を持っています。クール! : - )
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
要因には、あなたが(例えば、グラフ内の順序を実装する)、それらを必要なときに素晴らしいですが、時間の迷惑最もます。
ここでは私のもの。私はいつもメイン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"))
}
私はRコマンドの履歴を保存し、私はRを実行可能なたびに、それを持つように:
シェルまたは.bashrcの場合:
export R_HISTFILE=~/.Rhistory
.Rprofileでます:
.Last <- function() {
if (!any(commandArgs()=='--no-readline') && interactive()){
require(utils)
try(savehistory(Sys.getenv("R_HISTFILE")))
}
}
ここでは、私は窓を操作するための便利な見つける二つの機能があります。
まず、\
に/
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')
}
二つ目は新しいエクスプローラウィンドウで作業ディレクトリを開きます。
getw <- function() {
suppressWarnings(shell(paste("explorer", gsub('/', '\\\\', getwd()))))
}
私は(Linux上)COLUMNS環境変数から読み取ろうとする端末の完全な幅を、使用するには、この、よりダイナミックなトリックを持っています
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は、全幅を使用します。
私の個人的な機能とロードされるライブラリのほとんどは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")')
ここではMacとLinuxのために設計された私の〜/ .Rprofile の、からだ。
これらは見てエラーが容易になります。
options(showWarnCalls=T, showErrorCalls=T)
私はとても良い1に設定し、CRANのメニュー選択を嫌います。
options(repos=c("http://cran.cnr.Berkeley.edu","http://cran.stat.ucla.edu"))
その他の歴史!
Sys.setenv(R_HISTSIZE='100000')
次は、より安定しているので、私は大いにR.appに好む、とあなたは、ディレクトリであなたの仕事を整理することができた(端末からマックOSX上で動作しているためである。また、のhref = "HTTP <良いを取得することを確認してください://brenocon.com/.inputrc」のrel = "noreferrer">〜/ .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)
といくつかのライブラリをプリロード、
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
でそれを持っています。
ここでは私はあります:
.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
}
タグのみの「頭」を入力することなく、多少の頭」のようdata.frames表示を行います
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)
}
}
私は頻繁に私がコールすると、それらのコメントを解除することは非常に面倒なことができる必要があるデバッグ呼び出しのチェーンを持っています。 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
鉱山はあまりにも派手ではありません。
# 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)
私はそうすぐに接続する天の恵みである、MySQLデータベースからの多くの作業を行います。私は、私はすべての異なる名前を覚えておく必要がないようにavaialbleデータベースをリストアップする方法があった望みます。
この鉱山を含め、これまでに述べた。
もう見たいと思い:
- .セットです。幅()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"))
}
}
私はRStudioで「PDFをコンパイル」ボタンで動作するようにcacheSweave(またはpgfSweave)を取得するには、以下を使用します
library(cacheSweave)
assignInNamespace("RweaveLatex", cacheSweave::cacheSweaveDriver, "utils")
鉱山はoptions(menu.graphics=FALSE)
を含みR
こちらです。もにもに革新をもたらしました。思いのはなぜ特定の選択肢:
- で行った設定のデフォルト
stringsAsFactors
でん で非常に排水で引数として各時間のCSVを読み込みます。とはいえ、すでによく一部の小れぞれ---使用時のコードを書いつも利用するコンピュータをコンピューターを持たなかった。Rprofile.いつでも、どのトラブルが起のほトラブルのないセットが日常使いである。 - ない場合は負荷の
utils
パッケージ前options(error=recover)
, かな回復に配置されている場合に、内interactive()
ブロックです。 - 使用した
.db
私のdropbox設定によ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)
}
}
ここでの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
}
私は私のプロフィールで私の格子の色のテーマを設定しました。ここでは、2回の他の調整である私が使用します:
# 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)
私はパッケージのトップディレクトリを指す環境変数R_USER_WORKSPACEを持っています。 .Rprofileでは、私はRサブディレクトリ内のすべての.Rファイルを作業ディレクトリ(データ()が動作するように)とソースを設定する関数のdevlibを定義します。なお、上記ハドレーの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")
私は2つの機能が本当に必要が見つかりました:私はいくつかの機能に 第二に、それは関数名を含めdebug()
を設定していると私はバグを解決してきたので、私はすべての機能をundebug()
する最初のとき - 一つではない1。 undebug_all()
機能は最高ですのhref="https://stackoverflow.com/questions/12807237/r-undebug-all-functions">ここ受け入れ答えの
私は多くの機能を定義していると私は特定の変数の名前を探していたときにls()
のすべての結果、内それを見つけるのは難しいです。 lsnofun()
機能は、ここでのを投稿しました>本当に良いです。