programing

R 사용자 전문가, 의 기능.R 프로파일?

closeapi 2023. 6. 5. 23:55
반응형

R 사용자 전문가, 의 기능.R 프로파일?

저는 항상 다른 사람들의 스타트업 프로필 파일이 언어에 대해 유용하고 유익하다는 것을 발견했습니다.또한, Bash와 Vim에 대한 사용자 지정은 있지만 R에 대한 사용자 지정은 없습니다.

예를 들어, 제가 항상 원했던 한 가지는 창 단말기의 입력 및 출력 텍스트에 대한 다른 색상, 심지어 구문 강조도 있습니다.

여기 제 거예요.색칠하는 데 도움이 되지는 않겠지만 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, 내 공동 작성자들의 코드가 깨질 수도 있기 때문에, 나는 그것이 기본값이기를 바랍니다. 왜죠?

문자 벡터는 메모리를 적게 사용합니다(그러나 거의 사용하지 않습니다).

더 중요한 것은 다음과 같은 문제를 방지할 수 있다는 것입니다.

> 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을 실행할 때마다 사용할 수 있도록 하는 것이 좋습니다.

셸 또는 .bashrc에서:

export R_HISTFILE=~/.Rhistory

.R 프로파일:

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

다음은 창 작업에 유용한 두 가지 기능입니다.

첫 번째는 다음을 변환합니다.\/.

.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()))))
}

제 것은 여기 있어요.저는 항상 메인 크랜 저장소를 사용하며, 개발 중인 패키지 코드를 쉽게 소스할 수 있는 코드를 가지고 있습니다.

.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"))  
}

(리눅스에서) 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)

저는 CRAN 메뉴 선택이 싫으니 좋은 메뉴로 설정하세요.

options(repos=c("http://cran.cnr.Berkeley.edu","http://cran.stat.ucla.edu"))

더 많은 역사!

Sys.setenv(R_HISTSIZE='100000')

다음은 터미널에서 Mac OSX에서 실행하기 위한 것입니다(이는 R.app이 더 안정적이고 디렉토리별로 작업을 구성할 수 있으며 ~/.inputrc도 제대로 얻을 수 있기 때문에 R.app보다 훨씬 선호합니다).기본적으로 X11 디스플레이는 보기에 좋지 않습니다. 대신 GUI와 동일한 쿼츠 디스플레이를 제공합니다.if진술은 당신이 맥에서 터미널에서 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.frame을 '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)
   }
}

('헤드'를 출력에 자동으로 적용하는 방법은 무엇입니까?)

자주 전화해야 하는 디버그 호출이 있는데, 이 호출에 주석을 다는 것은 매우 지루할 수 있습니다.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 데이터베이스에서 많은 작업을 하기 때문에 바로 연결하는 것은 좋은 일입니다.사용 가능한 데이터베이스를 나열하여 다른 이름을 모두 기억할 필요가 없기를 바랄 뿐입니다.

스티븐 터너의 게시물.R 프로파일에는 몇 가지 유용한 별칭과 시작 기능이 있습니다.

나는 그의 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 설명서에 일부 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에서 CRAN 미러 선택을 위해 tclk 팝업을 비활성화/억제하는 것을 좋아하기 때문입니다.

제 것은 여기 있어요.너무 혁신적인 것은 없습니다.왜 특정한 선택을 하는지에 대한 생각:

  • 에 대한 기본 설정을 수행했습니다.stringsAsFactorsCSV를 읽을 때마다 인수로 전달하는 것이 매우 피곤하기 때문입니다.그렇긴 하지만, 제 컴퓨터가 없는 컴퓨터에서 제가 평소 사용하던 컴퓨터로 작성한 코드를 사용할 때 이미 약간의 번거로움이 있었습니다.R 프로파일.하지만, 저는 그것이 야기한 문제들로, 그것이 매일 그것을 설정하지 않은 문제들에 비해 창백하게 유지하고 있습니다.
  • 로드하지 않으면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)
    }
}

다음은 테이블을 LaTeX로 내보내는 데 사용할 수 있는 작은 조각입니다.내가 작성하는 많은 보고서에 대해 모든 열 이름이 수학 모드로 변경됩니다.나의 나머지.R 프로파일은 상당히 표준적이며 대부분 위에서 다룹니다.

# 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에서 나는 작업 디렉토리를 설정하고(데이터() 작동하도록) R 하위 디렉토리의 모든 .R 파일의 소스를 제공하는 함수 devlib를 정의합니다.위의 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")

저는 두 가지 기능이 정말 필요하다고 생각했습니다.내가 설정한 첫 번째debug()몇 가지 기능에서 그리고 나는 버그를 해결했다, 그래서 나는 원한다.undebug()모든 기능 - 하나씩이 아닙니다.undebug_all()여기서 수락된 답변으로 기능이 추가되었습니다.

둘째, 많은 함수를 정의하고 특정 변수 이름을 찾고 있을 때 모든 결과 내에서 찾기가 어렵습니다.ls()함수 이름을 포함합니다.lsnofun()여기에 게시된 기능은 정말 좋습니다.

언급URL : https://stackoverflow.com/questions/1189759/expert-r-users-whats-in-your-rprofile

반응형