전문가 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 :: Head) 그렇지 않으면 작동하지 않습니다.
# aliases
s <- base::summary
h <- utils::head
n <- base::names
편집 : 질문에 답하기 위해 색상 터미널에 다른 색상을 갖도록 패키지. 시원한! :-)
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을 실행할 때마다 사용할 수있게하는 것을 좋아합니다.
쉘 또는 .bashrc에서 :
export R_HISTFILE=~/.Rhistory
.rprofile에서 :
.Last <- function() {
if (!any(commandArgs()=='--no-readline') && interactive()){
require(utils)
try(savehistory(Sys.getenv("R_HISTFILE")))
}
}
다음은 Windows 작업에 편리한 두 가지 기능입니다.
첫 번째는 \
s to /
.
.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에서)에서 읽으려고합니다.
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")')
여기 내 것입니다 ~/.rprofile, Mac 및 Linux 용으로 설계되었습니다.
이로 인해 오류가 쉽게 볼 수 있습니다.
options(showWarnCalls=T, showErrorCalls=T)
나는 크랜 메뉴 선택을 싫어하므로 좋은 것으로 설정하십시오.
options(repos=c("http://cran.cnr.Berkeley.edu","http://cran.stat.ucla.edu"))
더 많은 역사!
Sys.setenv(R_HISTSIZE='100000')
다음은 터미널에서 MAC OSX에서 실행하는 것입니다 (R.App이 더 안정적이기 때문에 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)
그리고 몇 개의 라이브러리를 사전로드하고
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는 '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)
}
}
나는 종종 전화를 걸어야하는 디버그 전화 체인을 가지고 있으며 그것들을 무책임하게하는 것은 매우 지루할 수 있습니다. 의 도움으로 그래서 커뮤니티, 나는 다음 해결책을 찾아서 이것을 내 .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 데이터베이스를 나열하는 방법 만 있었으면 좋겠다.
스티븐 터너의 게시물 .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]
언급 된 아이디어를 포함하여 내 것이 있습니다.
보고 싶은 두 가지 :
- .set.width () / w () 인쇄 너비를 터미널 중 하나로 업데이트하십시오. 불행히도 나는 터미널 크기 조정에서 자동으로이를 수행 할 수있는 방법을 찾지 못했습니다. 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의 "Compile PDF"버튼과 함께 작동하기 위해 Cachesweave (또는 PGFSweave)를 얻기 위해 다음을 사용합니다.
library(cacheSweave)
assignInNamespace("RweaveLatex", cacheSweave::cacheSweaveDriver, "utils")
내 포함 options(menu.graphics=FALSE)
내가 좋아하기 때문에 r에서 크랜 미러 선택에 대한 tcltk 팝업을 비활성화/억제.
여기 내 것입니다. 너무 혁신적인 것은 없습니다. 특정 선택에 대한 생각 :
- 나는 기본값을 설정하면서 갔다
stringsAsFactors
CSV를 읽을 때마다 논쟁으로 전달하는 것이 극도로 배수되는 것을 발견했기 때문에. 하지만 매일 원인에 사용되는 문제와 비교할 때 문제가 생겼기 때문에 문제가 생겼습니다. - 로드하지 않으면
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)
}
}
다음은 테이블 내보내기 테이블을 사용하기위한 작은 스 니펫입니다. 유액. 내가 쓴 많은 보고서에 대해 모든 열 이름을 수학 모드로 변경합니다. 내 .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
}
내 격자 색상 테마를 내 프로필에서 설정했습니다. 내가 사용하는 다른 두 가지 조정은 다음과 같습니다.
# 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 I에서는 작업 디렉토리를 설정하는 함수 DevLib (데이터 ()가 작동) 및 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")